• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

FIWARE / trusted-issuers-list / 103

29 Oct 2026 11:53AM UTC coverage: 88.481% (+0.5%) from 88.017%
103

Pull #30

github

wistefan
clean
Pull Request #30: Ticket 95/work

177 of 223 branches covered (79.37%)

Branch coverage included in aggregate %.

36 of 37 new or added lines in 3 files covered. (97.3%)

714 of 784 relevant lines covered (91.07%)

0.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.57
/src/main/java/org/fiware/iam/rest/TrustedIssuersListController.java
1
/*
2
 * Copyright 2023 FIWARE Foundation e.V. and/or its affiliates
3
 * and other contributors as indicated by the @author tags.
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 * http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
package org.fiware.iam.rest;
18

19
import com.fasterxml.jackson.core.JsonProcessingException;
20
import com.fasterxml.jackson.databind.ObjectMapper;
21
import io.micronaut.core.annotation.Introspected;
22
import io.micronaut.core.annotation.Nullable;
23
import io.micronaut.data.model.Page;
24
import io.micronaut.data.model.Pageable;
25
import io.micronaut.data.model.Sort;
26
import io.micronaut.http.HttpResponse;
27
import io.micronaut.http.annotation.Controller;
28
import jakarta.transaction.Transactional;
29
import java.net.URI;
30
import java.util.List;
31
import java.util.Optional;
32
import lombok.RequiredArgsConstructor;
33
import lombok.extern.slf4j.Slf4j;
34
import org.fiware.iam.TILMapper;
35
import org.fiware.iam.exception.ConflictException;
36
import org.fiware.iam.repository.Credential;
37
import org.fiware.iam.repository.CredentialRepository;
38
import org.fiware.iam.repository.TrustedIssuer;
39
import org.fiware.iam.repository.TrustedIssuerRepository;
40
import org.fiware.iam.til.api.IssuerApi;
41
import org.fiware.iam.til.model.CredentialsVO;
42
import org.fiware.iam.til.model.ScopeTypeVO;
43
import org.fiware.iam.til.model.TrustedIssuerVO;
44
import org.fiware.iam.til.model.TrustedIssuersListResponseVO;
45

46
/** Implementation of the (proprietary) trusted-list api to manage the issuers. */
47
@Slf4j
1 ✔
48
@Controller("${general.basepath:/}")
49
@RequiredArgsConstructor
50
@Introspected
51
public class TrustedIssuersListController implements IssuerApi {
52

53
  public static final String HREF_TEMPLATE = "/v4/issuers/%s";
54

55
  private static final int DEFAULT_PAGE_SIZE = 10;
56
  private static final int MIN_PAGE_SIZE = 1;
57
  private static final int MAX_PAGE_SIZE = 100;
58
  private static final String SORT_FIELD = "did";
59
  private static final String NO_SCOPE_PROVIDED =
60
      "A scope is required - credentials without one cannot be revoked without affecting others.";
61
  private static final String SCOPE_TYPE_WITHOUT_SCOPE =
62
      "A scope type requires a scope - unscoped credentials cannot be addressed by type.";
63

64
  private final TrustedIssuerRepository trustedIssuerRepository;
65
  private final CredentialRepository credentialRepository;
66
  private final TILMapper trustedIssuerMapper;
67
  private final ObjectMapper objectMapper;
68

69
  /**
70
   * Returns a paginated list of DIDs of all trusted issuers, sorted alphabetically.
71
   *
72
   * @param pageSize maximum number of items per page (1-100, defaults to 10)
73
   * @param page zero-based page number (defaults to 0)
74
   * @return paginated response containing the issuer DIDs
75
   */
76
  @Override
77
  public HttpResponse<TrustedIssuersListResponseVO> getIssuers(
78
      @Nullable Integer pageSize, @Nullable Integer page) {
79
    pageSize = Optional.ofNullable(pageSize).orElse(DEFAULT_PAGE_SIZE);
1 ✔
80
    page = Optional.ofNullable(page).orElse(0);
1 ✔
81

82
    if (pageSize < MIN_PAGE_SIZE || pageSize > MAX_PAGE_SIZE) {
1 !
83
      throw new IllegalArgumentException("The requested page size is not supported.");
1 ✔
84
    }
85

86
    Sort didSort = Sort.unsorted().order(SORT_FIELD);
1 ✔
87
    Pageable pagination = Pageable.from(page, pageSize, didSort);
1 ✔
88
    Page<TrustedIssuer> result = trustedIssuerRepository.findAll(pagination);
1 ✔
89

90
    List<String> dids = result.getContent().stream().map(TrustedIssuer::getDid).toList();
1 ✔
91

92
    return HttpResponse.ok(
1 ✔
93
        new TrustedIssuersListResponseVO()
94
            .total((int) result.getTotalSize())
1 ✔
95
            .pageSize(result.getNumberOfElements())
1 ✔
96
            .page(page)
1 ✔
97
            .items(dids));
1 ✔
98
  }
99

100
  /**
101
   * Creates an issuer together with its credentials.
102
   *
103
   * <p>An issuer is usually created because something granted it a credential in the first place,
104
   * so the scope of that grant can be passed along and the credentials are attributed to it.
105
   * Without a scope the credentials are managed directly through the issuer endpoints, which means
106
   * no revocation will ever remove them - so a caller acting on behalf of a grant has to pass one.
107
   *
108
   * @param trustedIssuerVO the issuer and the credentials to create it with
109
   * @param scope what grants those credentials, or {@code null} if they are managed directly
110
   * @param scopeType the kind of thing the scope identifies, or {@code null} for an untyped grant
111
   * @return created, with the location of the issuer in the registry
112
   */
113
  @Transactional
114
  @Override
115
  public HttpResponse<Object> createTrustedIssuer(
116
      TrustedIssuerVO trustedIssuerVO, @Nullable String scope, @Nullable ScopeTypeVO scopeType) {
117
    if (scope == null && scopeType != null) {
1 ✔
118
      // no scoped operation could ever address an unscoped credential by its type
119
      throw new IllegalArgumentException(SCOPE_TYPE_WITHOUT_SCOPE);
1 ✔
120
    }
121
    if (scope != null) {
1 ✔
122
      requireScope(scope);
1 ✔
123
    }
124
    if (trustedIssuerRepository.existsById(trustedIssuerVO.getDid())) {
1 ✔
125
      throw new ConflictException("Issuer already exists.", trustedIssuerVO.getDid());
1 ✔
126
    }
127
    String type = toColumn(scopeType);
1 ✔
128
    TrustedIssuer trustedIssuer = trustedIssuerMapper.map(trustedIssuerVO);
1 ✔
129
    if (scope != null) {
1 ✔
130
      Optional.ofNullable(trustedIssuer.getCredentials())
1 ✔
131
          .orElseGet(List::of)
1 ✔
132
          .forEach(credential -> credential.setScope(scope).setScopeType(type));
1 ✔
133
    }
134
    TrustedIssuer persistedIssuer = trustedIssuerRepository.save(trustedIssuer);
1 ✔
135
    if (scope == null) {
1 ✔
136
      log.info("Issuer {} created", persistedIssuer.getDid());
1 ✔
137
    } else {
138
      log.info("Issuer {} created for scope {}", persistedIssuer.getDid(), describe(scope, type));
1 ✔
139
    }
140
    if (log.isDebugEnabled()) {
1 !
141
      log.debug("Issuer {} created with {}", persistedIssuer.getDid(), toJson(trustedIssuerVO));
×
142
    }
143
    return HttpResponse.created(URI.create(String.format(HREF_TEMPLATE, persistedIssuer.getDid())));
1 ✔
144
  }
145

146
  @Override
147
  public HttpResponse<Object> deleteIssuerById(String did) {
148
    Optional<TrustedIssuer> optionalTrustedIssuer = trustedIssuerRepository.getByDid(did);
1 ✔
149
    if (!trustedIssuerRepository.existsById(did)) {
1 ✔
150
      log.debug("Issuer {} not deleted, it does not exist", did);
1 ✔
151
      return HttpResponse.notFound();
1 ✔
152
    }
153
    trustedIssuerRepository.delete(optionalTrustedIssuer.get());
1 ✔
154
    log.info("Issuer {} deleted", did);
1 ✔
155
    return HttpResponse.noContent();
1 ✔
156
  }
157

158
  @Override
159
  public HttpResponse<TrustedIssuerVO> getIssuer(String did) {
160
    return trustedIssuerRepository
1 ✔
161
        .getByDid(did)
1 ✔
162
        .map(trustedIssuerMapper::map)
1 ✔
163
        .map(HttpResponse::ok)
1 ✔
164
        .orElseGet(HttpResponse::notFound);
1 ✔
165
  }
166

167
  /**
168
   * Sets the credentials granted by one scope to exactly the ones provided.
169
   *
170
   * <p>Credentials granted by another (scope, scopeType) pair, and credentials managed directly
171
   * through the issuer endpoints (which carry no scope), are left untouched. Replacing rather than
172
   * appending makes the operation idempotent: the callers react to notifications that are
173
   * redelivered on failure, so the same grant may well arrive twice.
174
   *
175
   * <p>The issuer is created when it is not known yet, which spares every caller a create-or-update
176
   * branch - and the race that comes with it.
177
   *
178
   * @param did the DID of the issuer
179
   * @param scope what grants the credentials, e.g. a ProductOrder id
180
   * @param credentialsVO the credentials this scope grants, possibly empty
181
   * @param scopeType the kind of thing the scope identifies, {@code null} addresses untyped grants
182
   * @return the issuer including all of its credentials
183
   */
184
  @Transactional
185
  @Override
186
  public HttpResponse<TrustedIssuerVO> replaceCredentialsByScope(
187
      String did,
188
      String scope,
189
      List<CredentialsVO> credentialsVO,
190
      @Nullable ScopeTypeVO scopeType) {
191

192
    requireScope(scope);
1 ✔
193
    String type = toColumn(scopeType);
1 ✔
194
    String grant = describe(scope, type);
1 ✔
195
    TrustedIssuer trustedIssuer =
1 ✔
196
        trustedIssuerRepository
197
            .getByDid(did)
1 ✔
198
            .orElseGet(
1 ✔
199
                () -> {
200
                  log.info("Issuer {} created for scope {}", did, grant);
1 ✔
201
                  return trustedIssuerRepository.save(new TrustedIssuer().setDid(did));
1 ✔
202
                });
203

204
    credentialRepository.deleteByTrustedIssuerDidAndScopeAndScopeType(did, scope, type);
1 ✔
205

206
    credentialsVO.stream()
1 ✔
207
        .map(trustedIssuerMapper::map)
1 ✔
208
        .map(
1 ✔
209
            credential ->
210
                credential.setScope(scope).setScopeType(type).setTrustedIssuer(trustedIssuer))
1 ✔
211
        .forEach(credentialRepository::save);
1 ✔
212
    if (credentialsVO.isEmpty()) {
1 ✔
213
      // nothing granted means the scope no longer grants anything
214
      log.info("Issuer {} revoked credentials of scope {}", did, grant);
1 ✔
215
    } else {
216
      log.info("Issuer {} granted credentials for scope {}", did, grant);
1 ✔
217
    }
218
    if (log.isDebugEnabled()) {
1 !
NEW
219
      log.debug("Issuer {} granted for scope {}: {}", did, grant, toJson(credentialsVO));
×
220
    }
221

222
    return trustedIssuerRepository
1 ✔
223
        .getByDid(did)
1 ✔
224
        .map(trustedIssuerMapper::map)
1 ✔
225
        .map(HttpResponse::ok)
1 ✔
226
        .orElseGet(HttpResponse::notFound);
1 ✔
227
  }
228

229
  /**
230
   * Deletes the credentials granted by one (scope, scopeType) pair and nothing else.
231
   *
232
   * <p>The issuer itself is kept even when no credential remains, so that an issuer somebody else
233
   * manages is not removed as a side effect of a revocation. An issuer without credentials is not
234
   * trusted for anything, which is the same outcome as before.
235
   *
236
   * @param did the DID of the issuer
237
   * @param scope what granted the credentials, e.g. a ProductOrder id
238
   * @param scopeType the kind of thing the scope identifies, {@code null} addresses untyped grants
239
   * @return no content, or not found if the issuer does not exist
240
   */
241
  @Transactional
242
  @Override
243
  public HttpResponse<Object> deleteCredentialsByScope(
244
      String did, String scope, @Nullable ScopeTypeVO scopeType) {
245
    requireScope(scope);
1 ✔
246
    String type = toColumn(scopeType);
1 ✔
247
    String grant = describe(scope, type);
1 ✔
248
    if (!trustedIssuerRepository.existsById(did)) {
1 ✔
249
      log.debug("Issuer {} has nothing to revoke for scope {}, it does not exist", did, grant);
1 ✔
250
      return HttpResponse.notFound();
1 ✔
251
    }
252
    credentialRepository.deleteByTrustedIssuerDidAndScopeAndScopeType(did, scope, type);
1 ✔
253
    log.info("Issuer {} revoked credentials of scope {}", did, grant);
1 ✔
254
    return HttpResponse.noContent();
1 ✔
255
  }
256

257
  /**
258
   * Reject a blank scope.
259
   *
260
   * <p>An empty scope would create a grant that no revocation can address precisely, which is the
261
   * problem the scope exists to solve.
262
   *
263
   * @param scope the scope to check
264
   */
265
  private static void requireScope(String scope) {
266
    if (scope == null || scope.isBlank()) {
1 !
267
      throw new IllegalArgumentException(NO_SCOPE_PROVIDED);
1 ✔
268
    }
269
  }
1 ✔
270

271
  /**
272
   * Store a scope type by its wire value, so the column reads the same as the API.
273
   *
274
   * @param scopeType the type of the grant, or {@code null} for an untyped grant
275
   * @return the wire value, or {@code null} for an untyped grant
276
   */
277
  @Nullable
278
  private static String toColumn(@Nullable ScopeTypeVO scopeType) {
279
    return scopeType == null ? null : scopeType.getValue();
1 ✔
280
  }
281

282
  /**
283
   * Render a grant for the log, keeping untyped grants as they were logged before types existed.
284
   *
285
   * @param scope the scope of the grant
286
   * @param scopeType the type of the grant, or {@code null}
287
   * @return the scope, followed by its type if there is one
288
   */
289
  private static String describe(String scope, @Nullable String scopeType) {
290
    return scopeType == null ? scope : scope + " of type " + scopeType;
1 ✔
291
  }
292

293
  /**
294
   * Render a request body for the debug log, the way it was received.
295
   *
296
   * @param body the issuer or credentials to render
297
   * @return the body as JSON, or its string form if it cannot be serialized
298
   */
299
  private String toJson(Object body) {
300
    try {
301
      return objectMapper.writeValueAsString(body);
×
302
    } catch (JsonProcessingException e) {
×
303
      return String.valueOf(body);
×
304
    }
305
  }
306

307
  /**
308
   * Replaces the credentials an issuer is managed with directly.
309
   *
310
   * <p>Credentials that were granted by a scope keep their own lifecycle and are <b>not</b>
311
   * touched: they belong to whatever granted them, and only that grant - or the deletion of the
312
   * whole issuer - may remove them. Replacing them here would let an unrelated administrative
313
   * update revoke access that an order paid for. Typed grants always carry a scope, so they are
314
   * kept as well.
315
   *
316
   * @param did the DID of the issuer
317
   * @param trustedIssuerVO the issuer with the credentials it is managed with directly
318
   * @return the issuer including its granted credentials, or not found if it does not exist
319
   */
320
  @Transactional
321
  @Override
322
  public HttpResponse<TrustedIssuerVO> updateIssuer(String did, TrustedIssuerVO trustedIssuerVO) {
323
    Optional<TrustedIssuer> optionalTrustedIssuer = trustedIssuerRepository.getByDid(did);
1 ✔
324
    if (optionalTrustedIssuer.isEmpty()) {
1 ✔
325
      log.debug("Issuer {} not updated, it does not exist", did);
1 ✔
326
      return HttpResponse.notFound();
1 ✔
327
    }
328
    if (!did.equals(trustedIssuerVO.getDid())) {
1 ✔
329
      throw new IllegalArgumentException("Did does not match the issuer object.");
1 ✔
330
    }
331

332
    List<Credential> directlyManaged =
1 ✔
333
        optionalTrustedIssuer.get().getCredentials().stream()
1 ✔
334
            .filter(credential -> credential.getScope() == null)
1 ✔
335
            .toList();
1 ✔
336
    credentialRepository.deleteAll(directlyManaged);
1 ✔
337
    trustedIssuerRepository.update(trustedIssuerMapper.map(trustedIssuerVO));
1 ✔
338
    log.info("Issuer {} updated", did);
1 ✔
339
    if (log.isDebugEnabled()) {
1 !
340
      log.debug("Issuer {} updated with {}", did, toJson(trustedIssuerVO));
×
341
    }
342

343
    return trustedIssuerRepository
1 ✔
344
        .getByDid(did)
1 ✔
345
        .map(trustedIssuerMapper::map)
1 ✔
346
        .map(HttpResponse::ok)
1 ✔
347
        .orElseGet(HttpResponse::notFound);
1 ✔
348
  }
349
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc