Skip to content

FEAT: Federated connections #1879

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
43 changes: 43 additions & 0 deletions src/errors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,46 @@ export class AccessTokenError extends SdkError {
this.code = code
}
}

/**
* Enum representing error codes related to federated connection access tokens.
*/
export enum FederatedConnectionAccessTokenErrorCode {
/**
* The session is missing.
*/
MISSING_SESSION = "missing_session",

/**
* The refresh token is missing.
*/
MISSING_REFRESH_TOKEN = "missing_refresh_token",

/**
* Failed to exchange the refresh token.
*/
FAILED_TO_EXCHANGE = "failed_to_exchange_refresh_token",
}

/**
* Error class representing an access token error for federated connections.
* Extends the `SdkError` class.
*/
export class FederatedConnectionsAccessTokenError extends SdkError {
/**
* The error code associated with the access token error.
*/
public code: string;

/**
* Constructs a new `FederatedConnectionsAccessTokenError` instance.
*
* @param code - The error code.
* @param message - The error message.
*/
constructor(code: string, message: string) {
super(message);
this.name = "FederatedConnectionAccessTokenError";
this.code = code;
}
}
118 changes: 117 additions & 1 deletion src/server/auth-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4012,7 +4012,123 @@ ca/T0LLtgmbMmxSv/MmzIg==
})
})
})
})
});

describe("federatedConnectionAccessToken", async () => {

it("Should exchange a refresh token for an access token", async () => {
const secret = await generateSecret(32)
const transactionStore = new TransactionStore({
secret,
})
const sessionStore = new StatelessSessionStore({
secret,
})
const authClient = new AuthClient({
transactionStore,
sessionStore,

domain: DEFAULT.domain,
clientId: DEFAULT.clientId,
clientSecret: DEFAULT.clientSecret,

secret,
appBaseUrl: DEFAULT.appBaseUrl,

fetch: getMockAuthorizationServer({
tokenEndpointResponse: {
token_type: "Bearer",
access_token: DEFAULT.accessToken,
expires_in: 86400, // expires in 10 days
} as oauth.TokenEndpointResponse,
}),
})

const expiresAt = Math.floor(Date.now() / 1000) - 10 * 24 * 60 * 60 // expired 10 days ago
const tokenSet = {
accessToken: DEFAULT.accessToken,
refreshToken: DEFAULT.refreshToken,
expiresAt,
};

const response = await authClient.federatedConnectionTokenExchange({ tokenSet, connection: "google-oauth2" });
const [error, federatedConnectionTokenSet] = response;
expect(error).toBe(null);
expect(federatedConnectionTokenSet).toEqual({
accessToken: DEFAULT.accessToken,
expiresAt: expect.any(Number),
})
})

it("should return an error if the discovery endpoint could not be fetched", async () => {
const secret = await generateSecret(32)
const transactionStore = new TransactionStore({
secret,
})
const sessionStore = new StatelessSessionStore({
secret,
})
const authClient = new AuthClient({
transactionStore,
sessionStore,

domain: DEFAULT.domain,
clientId: DEFAULT.clientId,
clientSecret: DEFAULT.clientSecret,

secret,
appBaseUrl: DEFAULT.appBaseUrl,

fetch: getMockAuthorizationServer({
discoveryResponse: new Response(null, { status: 500 }),
}),
})

const expiresAt = Math.floor(Date.now() / 1000) - 10 * 24 * 60 * 60 // expired 10 days ago
const tokenSet = {
accessToken: DEFAULT.accessToken,
refreshToken: DEFAULT.refreshToken,
expiresAt,
}

const [error, federatedConnectionTokenSet] = await authClient.federatedConnectionTokenExchange({ tokenSet, connection: "google-oauth2" })
expect(error?.code).toEqual("discovery_error")
expect(federatedConnectionTokenSet).toBeNull()
})

it("should return an error if the token set does not contain a refresh token", async () => {
const secret = await generateSecret(32)
const transactionStore = new TransactionStore({
secret,
})
const sessionStore = new StatelessSessionStore({
secret,
})
const authClient = new AuthClient({
transactionStore,
sessionStore,

domain: DEFAULT.domain,
clientId: DEFAULT.clientId,
clientSecret: DEFAULT.clientSecret,

secret,
appBaseUrl: DEFAULT.appBaseUrl,

fetch: getMockAuthorizationServer(),
})

const expiresAt = Math.floor(Date.now() / 1000) - 10 * 24 * 60 * 60 // expired 10 days ago
const tokenSet = {
accessToken: DEFAULT.accessToken,
expiresAt,
}

const [error, federatedConnectionTokenSet] = await authClient.federatedConnectionTokenExchange({ tokenSet, connection: "google-oauth2" })
expect(error?.code).toEqual("missing_refresh_token")
expect(federatedConnectionTokenSet).toBeNull()
})
});
})

const _authorizationServerMetadata = {
Expand Down
89 changes: 41 additions & 48 deletions src/server/auth-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,20 @@ import {
AuthorizationCodeGrantError,
AuthorizationError,
BackchannelLogoutError,
DiscoveryError,
InvalidStateError,
MissingStateError,
OAuth2Error,
SdkError,
} from "../errors"
import { LogoutToken, SessionData, TokenSet } from "../types"
import {
AuthServerMetadata,
MetadataDiscoverOptions,
} from "./authServerMetadata"
import FederatedConnections, {
FederatedConnectionTokenExchangeOptions,
FederatedConnectionTokenExchangeOutput,
} from "./federatedConnections/exchange"
import { AbstractSessionStore } from "./session/abstract-session-store"
import { TransactionState, TransactionStore } from "./transaction-store"
import { filterClaims } from "./user"
Expand Down Expand Up @@ -109,32 +116,31 @@ export interface AuthClientOptions {
export class AuthClient {
private transactionStore: TransactionStore
private sessionStore: AbstractSessionStore

private clientMetadata: oauth.Client
private clientSecret?: string
private clientAssertionSigningKey?: string | CryptoKey
private clientAssertionSigningAlg: string
private domain: string
private authorizationParameters: AuthorizationParameters
private pushedAuthorizationRequests: boolean

private appBaseUrl: string
private signInReturnToPath: string

private beforeSessionSaved?: BeforeSessionSavedHook
private onCallback: OnCallbackHook

private routes: Routes

private fetch: typeof fetch
private jwksCache: jose.JWKSCacheInput
private allowInsecureRequests: boolean
private httpOptions: () => oauth.HttpRequestOptions<"GET" | "POST">

private authorizationServerMetadata?: oauth.AuthorizationServer
private authServerMetadata: AuthServerMetadata
private metadataDiscoverOptions: MetadataDiscoverOptions
public federatedConnections: FederatedConnections

constructor(options: AuthClientOptions) {
// dependencies

this.authServerMetadata = new AuthServerMetadata()

this.fetch = options.fetch || fetch
this.jwksCache = options.jwksCache || {}
this.allowInsecureRequests = options.allowInsecureRequests ?? false
Expand Down Expand Up @@ -219,6 +225,18 @@ export class AuthClient {
process.env.NEXT_PUBLIC_ACCESS_TOKEN_ROUTE || "/auth/access-token",
...options.routes,
}

this.metadataDiscoverOptions = {
allowInsecureRequests: this.allowInsecureRequests,
fetch: this.fetch,
httpOptions: this.httpOptions,
issuer: this.issuer,
}

this.federatedConnections = new FederatedConnections({
metadataDiscoverOptions: this.metadataDiscoverOptions,
clientMetadata: this.clientMetadata,
})
}

async handler(req: NextRequest): Promise<NextResponse> {
Expand Down Expand Up @@ -326,7 +344,7 @@ export class AuthClient {
async handleLogout(req: NextRequest): Promise<NextResponse> {
const session = await this.sessionStore.get(req.cookies)
const [discoveryError, authorizationServerMetadata] =
await this.discoverAuthorizationServerMetadata()
await this.authServerMetadata.discover(this.metadataDiscoverOptions)

if (discoveryError) {
return new NextResponse(
Expand Down Expand Up @@ -383,7 +401,7 @@ export class AuthClient {
}

const [discoveryError, authorizationServerMetadata] =
await this.discoverAuthorizationServerMetadata()
await this.authServerMetadata.discover(this.metadataDiscoverOptions)

if (discoveryError) {
return this.onCallback(discoveryError, onCallbackCtx, null)
Expand Down Expand Up @@ -463,6 +481,7 @@ export class AuthClient {
sid: idTokenClaims.sid as string,
createdAt: Math.floor(Date.now() / 1000),
},
federatedConnectionsMap: {},
}

const res = await this.onCallback(null, onCallbackCtx, session)
Expand Down Expand Up @@ -605,7 +624,7 @@ export class AuthClient {
// the access token has expired and we have a refresh token
if (tokenSet.refreshToken && tokenSet.expiresAt <= Date.now() / 1000) {
const [discoveryError, authorizationServerMetadata] =
await this.discoverAuthorizationServerMetadata()
await this.authServerMetadata.discover(this.metadataDiscoverOptions)

if (discoveryError) {
console.error(discoveryError)
Expand Down Expand Up @@ -665,41 +684,6 @@ export class AuthClient {
return [null, tokenSet]
}

private async discoverAuthorizationServerMetadata(): Promise<
[null, oauth.AuthorizationServer] | [SdkError, null]
> {
if (this.authorizationServerMetadata) {
return [null, this.authorizationServerMetadata]
}

const issuer = new URL(this.issuer)

try {
const authorizationServerMetadata = await oauth
.discoveryRequest(issuer, {
...this.httpOptions(),
[oauth.customFetch]: this.fetch,
[oauth.allowInsecureRequests]: this.allowInsecureRequests,
})
.then((response) => oauth.processDiscoveryResponse(issuer, response))

this.authorizationServerMetadata = authorizationServerMetadata

return [null, authorizationServerMetadata]
} catch (e) {
console.error(
`An error occured while performing the discovery request. Please make sure the AUTH0_DOMAIN environment variable is correctly configured — the format must be 'example.us.auth0.com'. issuer=${issuer.toString()}, error:`,
e
)
return [
new DiscoveryError(
"Discovery failed for the OpenID Connect configuration."
),
null,
]
}
}

private async defaultOnCallback(
error: SdkError | null,
ctx: OnCallbackContext,
Expand All @@ -722,7 +706,7 @@ export class AuthClient {
logoutToken: string
): Promise<[null, LogoutToken] | [SdkError, null]> {
const [discoveryError, authorizationServerMetadata] =
await this.discoverAuthorizationServerMetadata()
await this.authServerMetadata.discover(this.metadataDiscoverOptions)

if (discoveryError) {
return [discoveryError, null]
Expand Down Expand Up @@ -814,7 +798,7 @@ export class AuthClient {
params: URLSearchParams
): Promise<[null, URL] | [Error, null]> {
const [discoveryError, authorizationServerMetadata] =
await this.discoverAuthorizationServerMetadata()
await this.authServerMetadata.discover(this.metadataDiscoverOptions)
if (discoveryError) {
return [discoveryError, null]
}
Expand Down Expand Up @@ -917,6 +901,15 @@ export class AuthClient {
? this.domain
: `https://${this.domain}`
}

public federatedConnectionTokenExchange = async (
options: FederatedConnectionTokenExchangeOptions
): Promise<FederatedConnectionTokenExchangeOutput> => {
return this.federatedConnections.federatedConnectionTokenExchange(
options,
await this.getClientAuth()
)
}
}

const encodeBase64 = (input: string) => {
Expand Down
Loading