Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
db4e382
refactor(core): share one set of Duration conversions
filipbodor Nov 1, 2026
c2a6860
refactor(core): classify statuses with HTTPResponse.Status
filipbodor Nov 1, 2026
25b18ee
docs(core): say where the never-indexed marking is lost
filipbodor Nov 1, 2026
54a5787
test(core): cover spaces around equals and a DPoP-only scope error
filipbodor Nov 1, 2026
e890629
test(core): show that a transient refresh failure keeps the session
filipbodor Nov 1, 2026
5e8833f
feat(core): revoke a token best effort within a time limit
filipbodor Nov 1, 2026
44e39c1
feat(core): return from sign-out once local state is cleared
filipbodor Nov 1, 2026
d3095da
fix(core): update the Keychain item in place instead of re-adding it
filipbodor Nov 1, 2026
e8ce516
docs: note the fractional device expiry in the changelog
filipbodor Nov 1, 2026
5efd0b6
fix(core): classify numbers outside 0...999 without trapping
filipbodor Nov 1, 2026
e31b08a
fix(core): match the Keychain item by identity, not accessibility
filipbodor Nov 1, 2026
7833026
feat(core): return an answered token exchange to its caller
filipbodor Nov 1, 2026
6821edd
refactor(core): name the revocation API for 1.0
filipbodor Nov 1, 2026
38cfafc
test(core): cover pending sign-out readers and bound async suites
filipbodor Nov 1, 2026
deacf02
docs: describe SwiftKeychain without naming a vendor
filipbodor Nov 1, 2026
b05d57a
docs(core): state which public enumerations are frozen
filipbodor Nov 1, 2026
a1f7209
test(core): keep the in-flight request inside the revocation limit
filipbodor Nov 1, 2026
8b405f2
fix(core): load the stored credential after pending store changes
filipbodor Nov 1, 2026
50aff95
feat(core): keep the rotated subject out of the exchange response
filipbodor Nov 1, 2026
ec80fa8
docs(core): give the real reason for the macOS login keychain
filipbodor Nov 1, 2026
b14df28
fix(core): filter loopback redirects by state before opening the browser
filipbodor Nov 1, 2026
1a26cb0
feat(core): let callers ignore the pending sign-out
filipbodor Nov 1, 2026
565f3e3
refactor(core): remove the application fields of Credential
filipbodor Nov 1, 2026
d57ced6
refactor(core): make PassportError members read-only to clients
filipbodor Nov 1, 2026
47d480f
refactor(core): name the loopback wait limit timeLimit
filipbodor Nov 1, 2026
f6b35e4
fix(core): refuse prompt none combined with other values
filipbodor Nov 1, 2026
83cf320
docs(core): fix stale references found in the full review
filipbodor Nov 1, 2026
b30479d
fix(core): read two-digit Retry-After years as RFC 9110 requires
filipbodor Nov 1, 2026
9f781d2
docs(core): state how an exchange response's refresh token is read
filipbodor Nov 1, 2026
af592f4
docs: release 1.0.0
filipbodor Nov 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 74 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,78 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [1.0.0] - 2026-11-01

The first stable release: from here on, a breaking change to the public API of `PassportKit` or `PassportKitTesting`
needs a new major version.

### Added

- `OAuthClient.revokeBestEffort(_:typeHint:timeLimit:)` revokes a token best effort (RFC 7009) and returns a
`RevocationOutcome` instead of throwing: `revoked`, `failed`, `timedOut` after the limit on the client's clock,
`cancelled`, or `skipped` without a revocation endpoint. It is for a token that never became a session, such as a
refresh token the app obtained but did not adopt. The limit defaults to `OAuthClient.revocationTimeLimit` (5
seconds), the limit `TokenManager` applies on sign-out, so apps need not copy it.
- `TokenManager.beginSignOut(revoke:)` clears the session without suspending and returns a `PendingSignOut`, whose
`result` (`get async`, like `Task.value`) waits for the store delete and the revocation (RFC 7009) and returns the
`SignOutResult`. Apps no longer need to watch for `.signedOut(.userInitiated)` to learn that the session is gone
(ADR 0014).

### Changed

- **Breaking:** `OAuthClient.beginAuthorization(_:)` throws `.invalidConfiguration` when `prompt` combines
`.noInteraction` (`none`) with another value, which OpenID Connect Core §3.1.2.1 forbids. Such a request used to be
sent.
- **Breaking:** `LoopbackRedirectListener.waitForCallback(timeout:accept:)` is `waitForCallback(timeLimit:accept:)`
and `LoopbackUserAgent(listener:timeout:openURL:)` is `LoopbackUserAgent(listener:timeLimit:openURL:)`, matching
the `timeLimit` of the other APIs that give up after a duration on the injected clock.
- **Breaking:** the members of `PassportError` (`code`, `recovery`, `statusCode`, `errorURI`, `underlying`) are
read-only outside the library, like `detail` already was. Create an error with the initializers instead of
changing one.
- **Breaking:** `SignOutResult.Revocation` is the top-level `RevocationOutcome`, shared by sign-out and
`OAuthClient.revokeBestEffort(_:typeHint:timeLimit:)`; `SignOutResult.revocation` has that type. Its cases are
unchanged.
- **Breaking:** `TokenManager.exchangeRefreshToken` returns the response when the server answered, even if the
session ended or was replaced while the request was in flight; it used to throw `.notAuthenticated` and drop the
issued token, which stayed valid at the server. The rotated subject still goes to the ended session's revocation
and the new session is not touched. Callers that must not use a token of an ended session check their own state
and revoke it as the audience client (ADR 0015).
- **Breaking:** the response of `TokenManager.exchangeRefreshToken` has `refreshToken` set to `nil`. The rotated
refresh token belongs to the session, which saves it; handing it out invited presenting it twice.
- `TokenManager.signOut(revoke:)` is `beginSignOut(revoke:)` followed by `await result`. The revocation's time
limit and its log line now run in a task the manager owns, so a revocation outcome is logged even when the caller
of `signOut` was cancelled. Results are unchanged.
- Every public enumeration states whether it is frozen. `TokenAcceptance` and `JSONValue` are frozen; `PassportEvent`,
`IssuerValidation`, `Discovery.Style`, `KeychainCredentialStore.Accessibility` and the enumerations of
`PassportKitTesting` may gain cases in a minor release, so a `switch` over them needs a `default`.

### Removed

- **Breaking:** `Credential.additionalFields` and the matching initializer parameter. Nothing in the library set or
read it, and `TokenManager` offered no way to fill it. Stored records that carry the field still decode; the field
is ignored.

### Fixed

- A `Retry-After` in the obsolete RFC 850 date form with a two-digit year up to 50 years ahead is read as a future
date (RFC 9110 §5.6.7); years 46 to 76 used to be read as the 20th century, which made the delay zero.
- `LoopbackUserAgent` installs its `state` filter before it opens the browser, so a request with another `state`
that reaches the listener while the browser opens is refused instead of being taken as the redirect.
- `TokenManager.load()` reads the store only after every save and delete decided before it, so a load that runs
while the delete of a signed-out or rejected session is still in progress no longer restores that session.
- `KeychainCredentialStore` updates an existing item in place instead of deleting it and adding it again, so a save
that fails (device locked, denied prompt) or a process that dies mid-save no longer loses the stored credential,
and stores writing the same item at once no longer fail with `errSecDuplicateItem`. A save whose payload could not
be archived fails with `.storageFailure` instead of storing an item without data.
- `KeychainCredentialStore` finds, replaces and deletes its item by class, service, account and access group, never
by accessibility class. An app that changes `accessibility` keeps its stored credential (on iOS it was no longer
found), and the next save moves the item to the new class.
- The documentation of `RequestAuthorizer.sign(_:for:)` for `HTTPRequest` and of `URLSessionTransport` states that
the never-indexed marking of `Authorization` (RFC 7541 §7.1.3) reaches the wire only through a transport that keeps
the indexing strategy of `HTTPFields`. `URLSessionTransport` converts to `URLRequest`, which drops it.
- `DeviceAuthorization.expiresAt` keeps the fractional part of a fractional `expires_in` instead of truncating it to
whole seconds.

## [0.3.2] - 2026-10-19

### Changed
Expand Down Expand Up @@ -324,7 +396,8 @@ unchanged: macOS 14, iOS 17, tvOS 17, watchOS 10 and visionOS 1.
- `FakeAuthorizationServer.authorizeInteractively` decodes the authorization request query as form data, so a `+` in
`scope` is a space.

[Unreleased]: https://github.com/slidoapp/PassportKit/compare/0.3.2...HEAD
[Unreleased]: https://github.com/slidoapp/PassportKit/compare/1.0.0...HEAD
[1.0.0]: https://github.com/slidoapp/PassportKit/compare/0.3.2...1.0.0
[0.3.2]: https://github.com/slidoapp/PassportKit/compare/0.3.1...0.3.2
[0.3.1]: https://github.com/slidoapp/PassportKit/compare/0.3.0...0.3.1
[0.3.0]: https://github.com/slidoapp/PassportKit/compare/0.2.0...0.3.0
Expand Down
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ keeping the session safe while refresh tokens rotate, and signing requests to pr
and the HTTP transport are injected, so every flow can be tested offline, and secrets never appear in logs,
descriptions or errors.

> **Status:** pre-1.0. The API can change in any minor version; see [CHANGELOG.md](CHANGELOG.md).
> **Status:** stable. The API follows [Semantic Versioning](https://semver.org): a breaking change needs a new major
> version. See [CHANGELOG.md](CHANGELOG.md).

## Features

Expand All @@ -21,7 +22,7 @@ descriptions or errors.
| Token exchange for other audiences and resources | RFC 8693 |
| Resource indicators | RFC 8707 |
| Authorization server metadata discovery | RFC 8414 |
| Token revocation on sign-out | RFC 7009 |
| Token revocation on sign-out, and best effort for any token | RFC 7009 |
| Bearer token requests with a single retry after a 401 | RFC 6750 |
| Native app redirects: `ASWebAuthenticationSession`, loopback | RFC 8252 |
| Granted scope on every token, and an acceptance hook before a token is used | RFC 6749 §3.3, §5.1 |
Expand All @@ -45,7 +46,7 @@ Add the package to `Package.swift`:

```swift
dependencies: [
.package(url: "https://github.com/slidoapp/PassportKit.git", from: "0.3.0")
.package(url: "https://github.com/slidoapp/PassportKit.git", from: "1.0.0")
],
targets: [
.target(name: "MyApp", dependencies: [
Expand All @@ -57,7 +58,8 @@ targets: [
]
```

Pin with `.upToNextMinor(from: "0.3.0")` if you need stability: a 0.x minor version can break the API.
`from: "1.0.0"` accepts every 1.x release, none of which breaks the API. Pin with `.upToNextMinor(from: "1.0.0")`
only if you want to take new features deliberately.

## Quick start

Expand Down
5 changes: 3 additions & 2 deletions Sources/PassportKit/Authorization/RequestAuthorizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,9 @@ public struct RequestAuthorizer: Sendable, CustomStringConvertible, CustomDebugS

/// Adds `Authorization: Bearer <token>` (RFC 6750 §2.1) and returns the token that was used.
///
/// Same rules as the `URLRequest` overload. The `Authorization` field is marked never-indexed (RFC 7541
/// §7.1.3).
/// Same rules as the `URLRequest` overload. The `Authorization` field is marked never indexed (RFC 7541
/// §7.1.3). The marking reaches the wire only if the code that sends the request keeps the `indexingStrategy`
/// of `HTTPFields`; converting to `URLRequest`, as ``URLSessionTransport`` does, drops it.
///
/// The signed request is your value: `HTTPTypes.HTTPRequest` prints its method, URL with query and, under
/// `dump`, every header field including `Authorization`. Never log a signed request.
Expand Down
3 changes: 2 additions & 1 deletion Sources/PassportKit/Client/AuthorizationRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public struct AuthorizationRequest: Sendable, Hashable {
/// `login_hint`, a hint for the authentication step (OpenID Connect Core §3.1.2.1).
public var loginHint: String?
/// `prompt` values (OpenID Connect Core §3.1.2.1), sent as one space-delimited parameter in the given order;
/// omitted when empty. ``Prompt/noInteraction`` must not be combined with other values.
/// omitted when empty. ``Prompt/noInteraction`` must not be combined with other values:
/// ``OAuthClient/beginAuthorization(_:)`` throws `invalidConfiguration` for such a list.
public var prompt: [Prompt]
/// Extension parameters appended after the standard ones; a colliding name is an `invalidConfiguration` error.
public var additionalParameters: AdditionalParameters
Expand Down
4 changes: 2 additions & 2 deletions Sources/PassportKit/Client/DeviceAuthorization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ extension DeviceAuthorization {
let pollInterval = seconds(DeviceAuthorizationResponseField.interval).flatMap {
$0.isFinite && $0 > 0 ? $0 : nil
}
if let pollInterval, pollInterval > Double(Self.maximumInterval.components.seconds) {
if let pollInterval, pollInterval > Self.maximumInterval.timeInterval {
throw PassportError(
.invalidResponse,
detail: "The device authorization response has an unusable polling interval."
Expand All @@ -158,7 +158,7 @@ extension DeviceAuthorization {
verificationURI: verificationURI,
verificationURIComplete: url(text(DeviceAuthorizationResponseField.verificationURIComplete)),
expiresIn: expiresIn,
expiresAt: wallClock.now().addingTimeInterval(Double(expiresIn.components.seconds)),
expiresAt: wallClock.now().addingTimeInterval(expiresIn.timeInterval),
interval: pollInterval.map { Duration.seconds($0) } ?? Self.defaultInterval,
stopwatch: Stopwatch(clock: clock)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,19 @@ extension OAuthClient {
/// authorization endpoint is configured, the endpoint carries a fragment or a query item the request also
/// sets, no ``ClientConfiguration/issuer`` is configured (the response `iss` could not be checked, RFC 9207
/// §2.4), the redirect URI is not absolute, has a fragment, or is plain `http` on a non-loopback host
/// (RFC 8252 §7.3, §8.3), a resource is invalid, the lifetime is not positive, or an additional parameter collides.
/// (RFC 8252 §7.3, §8.3), a resource is invalid, the lifetime is not positive, ``AuthorizationRequest/Prompt/noInteraction``
/// is combined with another `prompt` value (OpenID Connect Core §3.1.2.1), or an additional parameter collides.
public func beginAuthorization(_ request: AuthorizationRequest) throws -> PendingAuthorization {
_ = try requireIssuer()
let endpoint = try requireEndpoint(configuration.endpoints.authorization, name: "authorization")
try Self.validate(redirectURI: request.redirectURI)
guard request.lifetime > .zero else {
throw PassportError(.invalidConfiguration, detail: "The authorization lifetime must be positive.")
}
// OpenID Connect Core §3.1.2.1: `none` must not be combined with any other value.
guard !request.prompt.contains(.noInteraction) || request.prompt.count == 1 else {
throw PassportError(.invalidConfiguration, detail: "The prompt none cannot be combined with other values.")
}
guard var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false), components.fragment == nil
else {
throw PassportError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ extension OAuthClient {
try request.add(resources: resources)
request.additionalParameters = additionalParameters
let (response, body) = try await send(request)
guard (200..<300).contains(response.status.code) else {
guard response.status.kind == .successful else {
throw failure(response, body: body, to: request, context: .other)
}
return try DeviceAuthorization(
Expand Down Expand Up @@ -76,7 +76,7 @@ extension OAuthClient {
wait = backoff ?? interval
continue
}
if (200..<300).contains(response.status.code) {
if response.status.kind == .successful {
return try TokenResponse(parsing: body)
}
let error = failure(response, body: body, to: request, context: .deviceAuthorizationPoll)
Expand All @@ -95,7 +95,7 @@ extension OAuthClient {
if case .retryLater = error.recovery {
isTransient = true
} else {
isTransient = response.status.code == 429 || (500...599).contains(response.status.code)
isTransient = response.status.isTransient
}
guard isTransient else { throw error }
backoff = nextBackoff(after: backoff, interval: interval)
Expand Down
36 changes: 35 additions & 1 deletion Sources/PassportKit/Client/OAuthClient+Revocation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import Foundation
import HTTPTypes

extension OAuthClient {
/// The time limit ``TokenManager`` applies to the revocation on sign-out, and the default of
/// ``revokeBestEffort(_:typeHint:timeLimit:)``: five seconds.
public static let revocationTimeLimit = Duration.seconds(5)

/// Revokes a token (RFC 7009 §2).
///
/// Any 2xx response is success regardless of its body (§2.2: unknown or already revoked tokens also
Expand All @@ -15,8 +19,38 @@ extension OAuthClient {
request.add(OAuthParameter.token, token.reveal())
if let typeHint { request.add(OAuthParameter.tokenTypeHint, typeHint.rawValue) }
let (response, body) = try await send(request)
guard (200..<300).contains(response.status.code) else {
guard response.status.kind == .successful else {
throw failure(response, body: body, to: request, context: .other)
}
}

/// Revokes a token best effort and gives up after `timeLimit` on the client's clock (RFC 7009 §2).
///
/// For a token that never became a session, for example a refresh token the app obtained but did not hand
/// to a ``TokenManager``, so it can be invalidated at the server without holding up the app. Revocation is
/// a courtesy to the server, and the token may still be valid whatever the outcome (RFC 7009 §2.2).
///
/// Never throws. Returns ``RevocationOutcome/revoked`` for any 2xx (§2.2), ``RevocationOutcome/failed(_:)``
/// with the error ``revoke(_:typeHint:)`` would throw, ``RevocationOutcome/timedOut`` when `timeLimit` passed
/// first, ``RevocationOutcome/cancelled`` when the calling task was cancelled, and
/// ``RevocationOutcome/skipped`` when no revocation endpoint is configured. A timeout or cancellation cancels
/// the request; it may still have reached the server.
///
/// The default `timeLimit` is ``revocationTimeLimit``, the limit ``TokenManager`` uses on sign-out.
public func revokeBestEffort(
_ token: Secret, typeHint: TokenTypeHint? = nil, timeLimit: Duration = OAuthClient.revocationTimeLimit
) async -> RevocationOutcome {
guard configuration.endpoints.revocation != nil else { return .skipped }
do {
let finished = try await withTimeLimit(timeLimit, clock: clock) {
try await revoke(token, typeHint: typeHint)
return true
}
return finished == nil ? .timedOut : .revoked
} catch is CancellationError {
return .cancelled
} catch {
return .failed(error as? PassportError ?? PassportError(.transportFailure, underlying: error))
}
}
}
10 changes: 5 additions & 5 deletions Sources/PassportKit/Client/OAuthClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,21 +94,21 @@ public struct OAuthClient: Sendable, CustomStringConvertible, CustomDebugStringC
.response(
endpoint: request.endpoint,
statusCode: response.status.code,
errorCode: Self.errorCode(statusCode: response.status.code, body: body),
errorCode: Self.errorCode(status: response.status, body: body),
duration: stopwatch.elapsed
)
)
logger.debug(
"Request completed",
metadata: .request(
endpoint: request.endpoint, grantType: request.grantType, status: response.status.code,
errorCode: Self.errorCode(statusCode: response.status.code, body: body), duration: stopwatch.elapsed))
errorCode: Self.errorCode(status: response.status, body: body), duration: stopwatch.elapsed))
return (response, body)
}

/// The OAuth `error` member of a non-2xx response, only when it is a short plain token.
static func errorCode(statusCode: Int, body: Data) -> String? {
guard !(200..<300).contains(statusCode),
static func errorCode(status: HTTPResponse.Status, body: Data) -> String? {
guard status.kind != .successful,
case .object(let members)? = try? JSONDecoder().decode(JSONValue.self, from: body),
case .string(let code)? = members[ErrorResponseField.error],
(1...64).contains(code.count),
Expand All @@ -126,7 +126,7 @@ public struct OAuthClient: Sendable, CustomStringConvertible, CustomDebugStringC
exchange: Bool = false
) async throws -> TokenResponse {
let (response, body) = try await send(request)
guard (200..<300).contains(response.status.code) else {
guard response.status.kind == .successful else {
throw failure(response, body: body, to: request, context: context)
}
return try TokenResponse(parsing: body, exchange: exchange)
Expand Down
22 changes: 22 additions & 0 deletions Sources/PassportKit/Client/RevocationOutcome.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/// What happened to a best-effort token revocation (RFC 7009 §2): at sign-out
/// (``SignOutResult/revocation``) or with ``OAuthClient/revokeBestEffort(_:typeHint:timeLimit:)``.
///
/// Revocation is a courtesy to the server: whatever the outcome, the token may still be valid (§2.2). Cases may be
/// added in a minor release: the enumeration is not frozen, so a `switch` over it needs a `default`.
public enum RevocationOutcome: Sendable, Equatable {
/// Not attempted. At sign-out: revocation was not requested, the session had no refresh token, or no
/// revocation endpoint is configured. For ``OAuthClient/revokeBestEffort(_:typeHint:timeLimit:)``: no
/// revocation endpoint is configured.
case skipped
/// The server accepted the revocation (any 2xx, §2.2).
case revoked
/// The server or the network refused. The token may still be valid at the server.
case failed(PassportError)
/// The request did not finish within the time limit. It may still have reached the server.
case timedOut
/// The calling task was cancelled while it waited. At sign-out (``TokenManager/signOut(revoke:)`` or
/// ``PendingSignOut/result``) the revocation continues in the background and may still succeed, and the
/// session is cleared either way. For ``OAuthClient/revokeBestEffort(_:typeHint:timeLimit:)`` the request is
/// cancelled; it may still have reached the server.
case cancelled
}
Loading
Loading