Skip to content

Commit 3974e7c

Browse files
committed
Keep a pre-authorized Credential Offer's attributes with the offer
A pre-authorized Credential Offer wrote the user attributes it was made with into the shared user record, which OpenID Connect logins write too and which the Credential Endpoint, UserInfo, token introspection and access token minting read. So an offer naming an existing user replaced that user's claims until their next login, two offers for one user overwrote each other, and an offer made between a login and a credential request changed what that credential said. The attributes now travel with the offer: the pre-authorized code carries them (a nullable offer_claims column, migration 20261109000001), and the access token issued for it a copy. The offer adds a user record only when there is none, without claims, since codes and tokens have to name one. Nothing about a pre-authorized token reads the record's claims any more: the token's subject and JWT claims are resolved from the offer, the Credential Endpoint issues from the token's attributes, token introspection releases them, and UserInfo refuses such a token whatever its scopes. A code or token stored without the attributes is answered with server_error. The authorization code flow of credential issuance still reads the record of the user who authenticated. Assisted-by: Claude Code (claude-opus-5-5, implementation, tests & docs)
1 parent 955e62a commit 3974e7c

28 files changed

Lines changed: 1070 additions & 78 deletions

‎docs/3-oidc-configuration.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -769,8 +769,11 @@ requires `openid`, since its response types deliver an ID token.
769769

770770
The UserInfo endpoint refuses any access token without the `openid` scope in
771771
the same way, whatever this option says, so also one a refresh narrowed to
772-
scopes without it. A token of an OpenID4VCI flow, which need not carry the
773-
scope, is the exception.
772+
scopes without it. A token of the OpenID4VCI authorization code flow, which
773+
need not carry the scope, is the exception. A token of the pre-authorized code
774+
flow is refused whatever its scopes: no user authenticated for it, and it is
775+
about the attributes its Credential Offer was made with, not about the user
776+
record it names.
774777

775778
## Pushed Authorization Requests (PAR) and Request Objects
776779

‎docs/8-api.md‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,10 @@ address.
124124
source, that should be used to determine the user's email address attribute. Used if `users_email_attribute_name` is
125125
not specified, and transaction code protection is enabled.
126126
* __user_attributes__ (object, optional, no default): An object containing various user attributes. Used in
127-
pre-authorized code grant to populate credential data.
127+
pre-authorized code grant to populate credential data. The offer's pre-authorized code, and the access token issued
128+
for it, carry these attributes, and the credentials they buy are issued from them. They are not written to the user
129+
record: an offer naming an existing user leaves what OpenID Connect releases for that user as it was, and two offers
130+
naming the same user each issue their own attributes.
128131

129132
#### Response
130133

@@ -501,8 +504,12 @@ the user record as it is now: the same claims, from the same record, the
501504
UserInfo endpoint releases for that token, so a resource server which enforces
502505
its policy on the introspection response (RFC 7662 section 2.2 lets an
503506
implementation extend it with members of its own) sees what it would see at the
504-
UserInfo endpoint. Nothing is read from the token itself, which is a snapshot
505-
taken when it was minted, and the `claims` request parameter plays no part. The
507+
UserInfo endpoint. An access token of the OpenID4VCI pre-authorized code flow,
508+
which the UserInfo endpoint refuses, releases the claims of the attributes its
509+
Credential Offer was made with, which the token's record carries, instead,
510+
never those of the user record it names. Nothing is read from the token
511+
itself, which is a snapshot taken when it was minted, and the `claims` request
512+
parameter plays no part. The
506513
`sub` reported is the token's own, the subject it was minted with (see [the
507514
subject](3-oidc-configuration.md#the-subject)); a user claim of the same name
508515
as a token member does not displace it. (For an access token issued before the

‎src/Controllers/OAuth2/TokenIntrospectionController.php‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44

55
namespace SimpleSAML\Module\oidc\Controllers\OAuth2;
66

7+
use DateTimeImmutable;
78
use Exception;
89
use SimpleSAML\Error\ConfigurationError;
910
use SimpleSAML\Module\oidc\Bridges\OAuth2Bridge;
1011
use SimpleSAML\Module\oidc\Codebooks\ApiScopesEnum;
12+
use SimpleSAML\Module\oidc\Codebooks\FlowTypeEnum;
1113
use SimpleSAML\Module\oidc\Entities\AccessTokenEntity;
1214
use SimpleSAML\Module\oidc\Entities\UserEntity;
1315
use SimpleSAML\Module\oidc\Exceptions\AuthorizationException;
@@ -339,11 +341,12 @@ protected function resolveAccessTokenPayload(
339341
// The user claims of the released scopes, and only of those, so that a scope the decision took away can
340342
// not leave its claims behind. They are read from the resource owner's record as it is now: the claims
341343
// the UserInfo endpoint releases for the same token, from the same record, so a resource server learns the
342-
// same about the user whichever endpoint it asks. The 'claims' request parameter (OpenID Connect Core 1.0
343-
// section 5.5) targets the ID token and the UserInfo endpoint and plays no part here, as it plays none in
344-
// the access token's own user claims. Nothing is read from the presented token: it is a snapshot taken
345-
// when it was minted. A released identity claim which is not a non-empty string throws, and is answered
346-
// as the OP's failure.
344+
// same about the user whichever endpoint it asks. A token of the pre-authorized code flow, which UserInfo
345+
// refuses, releases the attributes of its Credential Offer instead (resolveResourceOwner()). The 'claims'
346+
// request parameter (OpenID Connect Core 1.0 section 5.5) targets the ID token and the UserInfo endpoint
347+
// and plays no part here, as it plays none in the access token's own user claims. Nothing is read from the
348+
// presented token: it is a snapshot taken when it was minted. A released identity claim which is not a
349+
// non-empty string throws, and is answered as the OP's failure.
347350
$userClaims = $resourceOwner instanceof UserEntity ?
348351
$this->claimTranslatorExtractor->extract($releasedScopes, $resourceOwner->getClaims()) :
349352
[];
@@ -399,6 +402,11 @@ protected function resolveDpopJkt(ParsedJws $accessToken): string|false|null
399402
/**
400403
* The resource owner whose user claims an active access token releases, as their record is now.
401404
*
405+
* A token of the pre-authorized code flow is about the attributes its Credential Offer was made with, which it
406+
* carries (PreAuthCodeGrant), and never about the claims of the record it names: that may be an existing user's,
407+
* holding that user's own. Its resource owner is a user built from the offer's attributes; the record still
408+
* decides whether the user exists. A token stored before tokens carried the attributes releases none.
409+
*
402410
* Null for a token issued without a user (a client credentials token, a pre-authorized code with no holder).
403411
* False when the token is not to be reported as active: its own record is gone, or its resource owner's is. The
404412
* validator has already looked the token's record up, so the former only happens when the record went between
@@ -449,7 +457,26 @@ protected function resolveResourceOwner(ParsedJws $accessToken): UserEntity|fals
449457
return false;
450458
}
451459

452-
return $user;
460+
if ($accessTokenEntity->getFlowTypeEnum() !== FlowTypeEnum::VciPreAuthorizedCode) {
461+
return $user;
462+
}
463+
464+
$offerClaims = $accessTokenEntity->getOfferClaims();
465+
466+
if (is_null($offerClaims)) {
467+
$this->loggerService->warning(
468+
sprintf(
469+
'Access token %s of the pre-authorized code flow carries no Credential Offer attributes (it was ' .
470+
'stored before tokens carried them). It releases no user claims.',
471+
$jti,
472+
),
473+
);
474+
}
475+
476+
// A user built from the offer's attributes, which is not stored; the record read above is left as it is.
477+
$now = new DateTimeImmutable();
478+
479+
return new UserEntity($userIdentifier, $now, $now, $offerClaims ?? []);
453480
}
454481

455482

‎src/Controllers/UserInfoController.php‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Psr\Http\Message\ServerRequestInterface;
99
use SimpleSAML\Error\UserNotFound;
1010
use SimpleSAML\Module\oidc\Bridges\PsrHttpBridge;
11+
use SimpleSAML\Module\oidc\Codebooks\FlowTypeEnum;
1112
use SimpleSAML\Module\oidc\Controllers\Traits\RequestTrait;
1213
use SimpleSAML\Module\oidc\Entities\AccessTokenEntity;
1314
use SimpleSAML\Module\oidc\Entities\UserEntity;
@@ -75,16 +76,27 @@ public function __invoke(ServerRequestInterface $request): Response
7576
// section 5.3), one granted the 'openid' scope. A plain OAuth 2.0 token
7677
// (ModuleConfig::OPTION_PLAIN_OAUTH2_AUTHORIZATION_CODE_ENABLED), or one a refresh narrowed to scopes
7778
// without 'openid', is refused as RFC 6750 section 3.1 has it, under the scheme it was presented under. A
78-
// token of an OpenID4VCI flow, which need not carry the scope, is answered as before.
79-
if (
80-
!in_array(ScopesEnum::OpenId->value, $scopes, true) &&
81-
$accessToken->getFlowTypeEnum()?->isVciFlow() !== true
82-
) {
79+
// token of the OpenID4VCI authorization code flow, which need not carry the scope, is answered as before: a
80+
// user authenticated for it. A token of the pre-authorized code flow is refused whatever its scopes: nobody
81+
// authenticated, it is about the attributes its Credential Offer was made with (which it carries for the
82+
// Credential Endpoint), and its user record, which may be an existing user's, is not what it is about.
83+
$flowType = $accessToken->getFlowTypeEnum();
84+
$isGrantedOpenId = in_array(ScopesEnum::OpenId->value, $scopes, true);
85+
$refusal = null;
86+
87+
if ($flowType === FlowTypeEnum::VciPreAuthorizedCode) {
88+
$refusal = 'The access token was issued for a pre-authorized Credential Offer, for credential issuance ' .
89+
'only.';
90+
} elseif (!$isGrantedOpenId && $flowType !== FlowTypeEnum::VciAuthorizationCode) {
91+
$refusal = "The access token was not granted the 'openid' scope.";
92+
}
93+
94+
if ($refusal !== null) {
8395
/** @psalm-suppress MixedAssignment */
8496
$scheme = $authorization->getAttribute(BearerTokenValidator::ATTRIBUTE_ACCESS_TOKEN_SCHEME);
8597

8698
throw OidcServerException::insufficientScope(
87-
"The access token was not granted the 'openid' scope.",
99+
$refusal,
88100
OidcServerException::buildResourceChallenges(
89101
AccessTokenTypesEnum::tryFrom(is_string($scheme) ? $scheme : ''),
90102
'insufficient_scope',

‎src/Controllers/VerifiableCredentials/CredentialIssuerCredentialController.php‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,24 @@ protected function issueCredential(Request $request): Response
303303
);
304304
}
305305

306+
// What the credential says about the user. A token of the pre-authorized code flow carries the attributes its
307+
// Credential Offer was made with (PreAuthCodeGrant), and the credential is issued from those, never from the
308+
// user record: the record of an existing user holds that user's own claims, and a login can rewrite it
309+
// between the offer and this request. A token of the authorization code flow is about the user who
310+
// authenticated, as their record is now.
311+
$userAttributes = $accessToken->getFlowTypeEnum() === FlowTypeEnum::VciPreAuthorizedCode ?
312+
$accessToken->getOfferClaims() :
313+
$userEntity->getClaims();
314+
315+
if ($userAttributes === null) {
316+
$this->loggerService->error(
317+
'CredentialIssuerCredentialController::credential: Access token of the pre-authorized code flow ' .
318+
'carries no Credential Offer attributes (it was stored before tokens carried them).',
319+
['accessTokenId' => $accessToken->getIdentifier()],
320+
);
321+
throw OidcServerException::serverError('The access token carries no Credential Offer attributes.');
322+
}
323+
306324
// A request names its credential by `credential_identifier` when the token response returned authorization
307325
// details, by `credential_configuration_id` otherwise, and never by both (OpenID4VCI 1.0 section 8.2).
308326
// Which members it carries is read by name rather than by value, so a member sent as null still counts as
@@ -600,8 +618,6 @@ protected function issueCredential(Request $request): Response
600618
$sub = $validatedProof?->getSubject() ??
601619
($this->moduleConfig->getIssuer() . '/sub/' . $userId);
602620

603-
$userAttributes = $userEntity->getClaims();
604-
605621
// Get valid claim paths so we can check if the user attribute is allowed to be included in the credential,
606622
// as per the credential configuration supported configuration.
607623
$validClaimPaths = $this->moduleConfig->getVciValidCredentialClaimPathsFor($resolvedCredentialIdentifier);

‎src/Entities/AccessTokenEntity.php‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ class AccessTokenEntity implements AccessTokenEntityInterface, EntityStringRepre
6060
* @param string|null $dpopJkt The JWK SHA-256 thumbprint of the DPoP key the token is bound to, written in the
6161
* JWT as its `cnf` claim (RFC 9449 section 6.1); null for a token bound to no key. Not persisted, for the same
6262
* reason as the subject: whatever reads the binding reads the JWT.
63+
* @param array|null $offerClaims The user attributes the pre-authorized Credential Offer the token was issued
64+
* for was made with, copied from its code (PreAuthCodeGrant), so that a code purged after it expires can not
65+
* take them from a token which still lives. What the token is about is read from these, never from the user
66+
* record. Null for a token of any other flow, and for a pre-authorized one stored before tokens carried them;
67+
* an empty array is an offer made with no attributes.
6368
*/
6469
public function __construct(
6570
string $id,
@@ -80,6 +85,7 @@ public function __construct(
8085
protected readonly ?string $subject = null,
8186
protected readonly array $userClaims = [],
8287
protected readonly ?string $dpopJkt = null,
88+
protected readonly ?array $offerClaims = null,
8389
) {
8490
if ($id === '') {
8591
throw new InvalidArgumentException('Access token identifier cannot be empty.');
@@ -171,6 +177,9 @@ public function getState(): array
171177
'bound_client_id' => $this->boundClientId,
172178
'bound_redirect_uri' => $this->boundRedirectUri,
173179
'issuer_state' => $this->issuerState,
180+
'offer_claims' => is_array($this->offerClaims) ?
181+
json_encode($this->offerClaims, JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE) :
182+
null,
174183
];
175184
}
176185

@@ -302,4 +311,10 @@ public function getIssuerState(): ?string
302311
{
303312
return $this->issuerState;
304313
}
314+
315+
316+
public function getOfferClaims(): ?array
317+
{
318+
return $this->offerClaims;
319+
}
305320
}

‎src/Entities/AuthCodeEntity.php‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ class AuthCodeEntity implements AuthCodeEntityInterface, MementoInterface
2929
* @param \League\OAuth2\Server\Entities\ScopeEntityInterface[] $scopes
3030
* @param string|null $dpopJkt The JWK SHA-256 thumbprint of the key the code is bound to (RFC 9449 section 10),
3131
* which the token request has to bring a DPoP proof by; null for a code bound to none.
32+
* @param array|null $offerClaims The user attributes a pre-authorized Credential Offer was made with
33+
* (CredentialOfferUriFactory::buildPreAuthorized()), which the credentials it buys are issued from; null for
34+
* any other code, and for a pre-authorized one stored before codes carried them. An empty array is an offer
35+
* made with no attributes, not the absence of one.
3236
*/
3337
public function __construct(
3438
string $id,
@@ -46,6 +50,7 @@ public function __construct(
4650
protected readonly ?string $boundRedirectUri = null,
4751
protected readonly ?string $issuerState = null,
4852
protected readonly ?string $dpopJkt = null,
53+
protected readonly ?array $offerClaims = null,
4954
) {
5055
if ($id === '') {
5156
throw new InvalidArgumentException('Authorization code identifier cannot be empty.');
@@ -85,6 +90,10 @@ public function getState(): array
8590
'bound_redirect_uri' => $this->boundRedirectUri,
8691
'issuer_state' => $this->issuerState,
8792
'dpop_jkt' => $this->dpopJkt,
93+
// Encoded as the user record encodes its claims (UserEntity::getState()), which held these before.
94+
'offer_claims' => is_array($this->offerClaims) ?
95+
json_encode($this->offerClaims, JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE) :
96+
null,
8897
];
8998
}
9099

@@ -135,4 +144,10 @@ public function getDpopJkt(): ?string
135144
{
136145
return $this->dpopJkt;
137146
}
147+
148+
149+
public function getOfferClaims(): ?array
150+
{
151+
return $this->offerClaims;
152+
}
138153
}

‎src/Factories/CredentialOfferUriFactory.php‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -167,14 +167,13 @@ public function buildPreAuthorized(
167167
$this->loggerService->info('Generated user identifier based on credential-offer attributes.');
168168
}
169169

170-
$oldUserEntity = $this->userRepository->getUserEntityByIdentifier($userId);
171-
172-
$userEntity = $this->userEntityFactory->fromData($userId, $userAttributes);
173-
174-
if ($oldUserEntity instanceof UserEntity) {
175-
$this->userRepository->update($userEntity);
176-
} else {
177-
$this->userRepository->add($userEntity);
170+
// The attributes travel with the code, and from it with the access token (PreAuthCodeGrant), and the
171+
// credentials the code buys are issued from them. They are never written to the user record: the record of
172+
// an existing user holds that user's own claims, which OpenID Connect and the authorization code flow of
173+
// credential issuance read, and two offers naming the same identifier would overwrite each other there.
174+
// Codes and tokens have to name a stored user, so a record with no claims is added when there is none.
175+
if (!$this->userRepository->getUserEntityByIdentifier($userId) instanceof UserEntity) {
176+
$this->userRepository->add($this->userEntityFactory->fromData($userId));
178177
}
179178

180179
$txCode = null;
@@ -201,6 +200,7 @@ public function buildPreAuthorized(
201200
redirectUri: 'openid-credential-offer://',
202201
flowTypeEnum: FlowTypeEnum::VciPreAuthorizedCode,
203202
txCode: $txCode instanceof TxCode ? $txCode->getCodeAsString() : null,
203+
offerClaims: $userAttributes,
204204
);
205205
$this->authCodeRepository->persistNewAuthCode($authCode);
206206
break;

‎src/Factories/Entities/AccessTokenEntityFactory.php‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ public function __construct(
3131
* @param array<non-empty-string, mixed> $userClaims The user claims placed in the JWT next to 'sub'.
3232
* @param string|null $dpopJkt The thumbprint of the DPoP key the token is bound to; null for none, and for an
3333
* entity rehydrated from storage.
34+
* @param array|null $offerClaims The attributes of the pre-authorized Credential Offer the token was issued for;
35+
* null for a token of any other flow.
3436
*/
3537
public function fromData(
3638
string $id,
@@ -49,6 +51,7 @@ public function fromData(
4951
?string $subject = null,
5052
array $userClaims = [],
5153
?string $dpopJkt = null,
54+
?array $offerClaims = null,
5255
): AccessTokenEntity {
5356
return new AccessTokenEntity(
5457
$id,
@@ -69,6 +72,7 @@ public function fromData(
6972
subject: $subject,
7073
userClaims: $userClaims,
7174
dpopJkt: $dpopJkt,
75+
offerClaims: $offerClaims,
7276
);
7377
}
7478

@@ -123,6 +127,7 @@ public function fromState(array $state): AccessTokenEntity
123127
$boundClientId = empty($state['bound_client_id']) ? null : (string)$state['bound_client_id'];
124128
$boundRedirectUri = empty($state['bound_redirect_uri']) ? null : (string)$state['bound_redirect_uri'];
125129
$issuerState = empty($state['issuer_state']) ? null : (string)$state['issuer_state'];
130+
$offerClaims = $this->offerClaimsFromState($state);
126131

127132
return $this->fromData(
128133
$id,
@@ -138,6 +143,34 @@ public function fromState(array $state): AccessTokenEntity
138143
$boundClientId,
139144
$boundRedirectUri,
140145
$issuerState,
146+
offerClaims: $offerClaims,
141147
);
142148
}
149+
150+
151+
/**
152+
* The attributes of the pre-authorized Credential Offer the token was issued for, or null for a token which
153+
* carries none: one of another flow, or a state written before tokens carried them (a cached one included),
154+
* which has no such entry. An empty JSON array stays an empty array, an offer made with no attributes.
155+
*
156+
* @throws \JsonException
157+
* @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException
158+
*/
159+
protected function offerClaimsFromState(array $state): ?array
160+
{
161+
if (!isset($state['offer_claims'])) {
162+
return null;
163+
}
164+
165+
/** @psalm-suppress MixedAssignment */
166+
$offerClaims = is_string($state['offer_claims']) ?
167+
json_decode($state['offer_claims'], true, 512, JSON_THROW_ON_ERROR) :
168+
null;
169+
170+
if (!is_array($offerClaims)) {
171+
throw OidcServerException::serverError('Invalid Access Token Entity state: offer claims');
172+
}
173+
174+
return $offerClaims;
175+
}
143176
}

0 commit comments

Comments
 (0)