Skip to content

Commit

Permalink
Introduce AuthenticationKeeper actor to serialize authn modification (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
edigaryev authored Nov 6, 2023
1 parent f4bc02d commit 70040b6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
25 changes: 25 additions & 0 deletions Sources/tart/OCI/AuthenticationKeeper.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import Foundation

actor AuthenticationKeeper {
var authentication: Authentication? = nil

func set(_ authentication: Authentication) {
self.authentication = authentication
}

func header() -> (String, String)? {
if let authentication = authentication {
// Do not suggest any headers if the
// authentication token has expired
if !authentication.isValid() {
return nil
}

return authentication.header()
}

// Do not suggest any headers if the
// authentication token is not set
return nil
}
}
15 changes: 4 additions & 11 deletions Sources/tart/OCI/Registry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,7 @@ class Registry {
private let baseURL: URL
let namespace: String
let credentialsProviders: [CredentialsProvider]

var currentAuthToken: Authentication? = nil
let authenticationKeeper = AuthenticationKeeper()

var host: String? {
guard let host = baseURL.host else { return nil }
Expand Down Expand Up @@ -305,11 +304,6 @@ class Registry {
request.httpBody = body
}

// Invalidate token if it has expired
if currentAuthToken?.isValid() == false {
currentAuthToken = nil
}

var (channel, response) = try await authAwareRequest(request: request, viaFile: viaFile)

if doAuth && response.statusCode == HTTPCode.Unauthorized.rawValue {
Expand All @@ -331,7 +325,7 @@ class Registry {

if wwwAuthenticate.scheme.lowercased() == "basic" {
if let (user, password) = try lookupCredentials() {
currentAuthToken = BasicAuthentication(user: user, password: password)
await authenticationKeeper.set(BasicAuthentication(user: user, password: password))
}

return
Expand Down Expand Up @@ -378,7 +372,7 @@ class Registry {
+ "while retrieving an authentication token", details: data.asText())
}

currentAuthToken = try TokenResponse.parse(fromData: data)
await authenticationKeeper.set(try TokenResponse.parse(fromData: data))
}

private func lookupCredentials() throws -> (String, String)? {
Expand All @@ -399,8 +393,7 @@ class Registry {
private func authAwareRequest(request: URLRequest, viaFile: Bool = false) async throws -> (AsyncThrowingChannel<Data, Error>, HTTPURLResponse) {
var request = request

if let token = currentAuthToken {
let (name, value) = token.header()
if let (name, value) = await authenticationKeeper.header() {
request.addValue(value, forHTTPHeaderField: name)
}

Expand Down

0 comments on commit 70040b6

Please sign in to comment.