/**
 * Copyright (c) 2020, 2021 Oracle and/or its affiliates.  All rights reserved.
 * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
 */ import { readFileSync } from "fs" ; import FederationClient from "./models/federation-client" ; import SessionKeySupplier from "./models/session-key-supplier" ; import SecurityTokenAdapter from "./security-token-adapter" ; /**
 * This class gets a security token from file.
 */ export default class FileBasedResourcePrincipalFederationClient implements FederationClient { private securityTokenAdapter : SecurityTokenAdapter ; constructor ( private sessionKeySupplier , private resourcePrincipalSessionTokenPath ) { this . sessionKeySupplier = sessionKeySupplier ; this . securityTokenAdapter = new SecurityTokenAdapter ( "" , sessionKeySupplier ) ; this . resourcePrincipalSessionTokenPath = resourcePrincipalSessionTokenPath ; } return throws async getSecurityToken ( ) { if ( this . securityTokenAdapter . isValid ( ) ) { return this . securityTokenAdapter . getSecurityToken ( ) ; } return await this . refreshAndGetSecurityTokenInner ( true ) ; } param key return async getStringClaim ( key ) { await this . refreshAndGetSecurityToken ( ) ; return this . securityTokenAdapter . getStringClaim ( key ) ; } async refreshAndGetSecurityToken ( ) { return await this . refreshAndGetSecurityTokenInner ( false ) ; } private async refreshAndGetSecurityTokenInner ( doFinalTokenValidityCheck ) { if ( ! doFinalTokenValidityCheck || ! this . securityTokenAdapter . isValid ( ) ) { this . sessionKeySupplier . refreshKeys ( ) ; this . securityTokenAdapter = this . getSecurityTokenFromFile ( ) ; return this . securityTokenAdapter . getSecurityToken ( ) ; } return this . securityTokenAdapter . getSecurityToken ( ) ; } return protected getSecurityTokenFromFile ( ) { const keyPair = this . sessionKeySupplier . getKeyPair ( ) ; if ( ! keyPair ) { throw Error ( "Keypair for session was not provided" ) ; } let securityToken = "" ; try { securityToken = readFileSync ( this . resourcePrincipalSessionTokenPath , "utf8" ) ; } catch ( e ) { throw Error ( `Failed to read token due to error: ${ e }` ) ; } return new SecurityTokenAdapter ( securityToken , this . sessionKeySupplier ) ; } }