import{a as M,c as u}from"./chunk-IY2KKEUD.js";import"./chunk-ZCWB3HFB.js";import"./chunk-WI7DO2VU.js";import{a as S,b as s}from"./chunk-TX7AAHER.js";import"./chunk-FSRPMVAS.js";import{parse as $}from"url";import{Buffer as W}from"buffer";import{request as K}from"http";function m(e){return new Promise((t,n)=>{let o=K({method:"GET",...e,hostname:e.hostname?.replace(/^\[(.+)\]$/,"$1")});o.on("error",r=>{n(Object.assign(new S("Unable to connect to instance metadata service"),r)),o.destroy()}),o.on("timeout",()=>{n(new S("TimeoutError from instance metadata service")),o.destroy()}),o.on("response",r=>{let{statusCode:a=400}=r;(a<200||300<=a)&&(n(Object.assign(new S("Error response received from instance metadata service"),{statusCode:a})),o.destroy());let f=[];r.on("data",i=>{f.push(i)}),r.on("end",()=>{t(W.concat(f)),o.destroy()})}),o.end()})}var N=e=>!!e&&typeof e=="object"&&typeof e.AccessKeyId=="string"&&typeof e.SecretAccessKey=="string"&&typeof e.Token=="string"&&typeof e.Expiration=="string",g=e=>({accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretAccessKey,sessionToken:e.Token,expiration:new Date(e.Expiration),...e.AccountId&&{accountId:e.AccountId}});var pe=1e3,me=0,h=({maxRetries:e=0,timeout:t=1e3})=>({maxRetries:e,timeout:t});var A=(e,t)=>{let n=e();for(let o=0;o<t;o++)n=n.catch(e);return n};var C="AWS_CONTAINER_CREDENTIALS_FULL_URI",O="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",y="AWS_CONTAINER_AUTHORIZATION_TOKEN",Ne=(e={})=>{let{timeout:t,maxRetries:n}=h(e);return()=>A(async()=>{let o=await j({logger:e.logger}),r=JSON.parse(await B(t,o));if(!N(r))throw new s("Invalid response received from instance metadata service.",{logger:e.logger});return g(r)},n)},B=async(e,t)=>(process.env[y]&&(t.headers={...t.headers,Authorization:process.env[y]}),(await m({...t,timeout:e})).toString()),G="169.254.170.2",q={localhost:!0,"127.0.0.1":!0},H={"http:":!0,"https:":!0},j=async({logger:e})=>{if(process.env[O])return{hostname:G,path:process.env[O]};if(process.env[C]){let t=$(process.env[C]);if(!t.hostname||!(t.hostname in q))throw new s(`${t.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:e});if(!t.protocol||!(t.protocol in H))throw new s(`${t.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:e});return{...t,port:t.port?parseInt(t.port,10):void 0}}throw new s(`The container metadata credential provider cannot be used unless the ${O} or ${C} environment variable is set`,{tryNextLink:!1,logger:e})};var v=class e extends s{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(t,n=!0){super(t,n),this.tryNextLink=n,Object.setPrototypeOf(this,e.prototype)}};var _;(function(e){e.IPv4="http://169.254.169.254",e.IPv6="http://[fd00:ec2::254]"})(_||(_={}));var Y="AWS_EC2_METADATA_SERVICE_ENDPOINT",J="ec2_metadata_service_endpoint",P={environmentVariableSelector:e=>e[Y],configFileSelector:e=>e[J],default:void 0};var p;(function(e){e.IPv4="IPv4",e.IPv6="IPv6"})(p||(p={}));var z="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",X="ec2_metadata_service_endpoint_mode",R={environmentVariableSelector:e=>e[z],configFileSelector:e=>e[X],default:p.IPv4};var D=async()=>M(await Z()||await Q()),Z=async()=>u(P)(),Q=async()=>{let e=await u(R)();switch(e){case p.IPv4:return _.IPv4;case p.IPv6:return _.IPv6;default:throw new Error(`Unsupported endpoint mode: ${e}. Select from ${Object.values(p)}`)}};var ee="https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html",w=(e,t)=>{let n=300+Math.floor(Math.random()*300),o=new Date(Date.now()+n*1e3);t.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(o)}.
For more information, please visit: `+ee);let r=e.originalExpiration??e.expiration;return{...e,...r?{originalExpiration:r}:{},expiration:o}};var b=(e,t={})=>{let n=t?.logger||console,o;return async()=>{let r;try{r=await e(),r.expiration&&r.expiration.getTime()<Date.now()&&(r=w(r,n))}catch(a){if(o)n.warn("Credential renew failed: ",a),r=w(o,n);else throw a}return o=r,r}};var k="/latest/meta-data/iam/security-credentials/",te="/latest/api/token",x="AWS_EC2_METADATA_V1_DISABLED",F="ec2_metadata_v1_disabled",L="x-aws-ec2-metadata-token",Je=(e={})=>b(oe(e),{logger:e.logger}),oe=(e={})=>{let t=!1,{logger:n,profile:o}=e,{timeout:r,maxRetries:a}=h(e),f=async(i,E)=>{if(t||E.headers?.[L]==null){let c=!1,d=!1,U=await u({environmentVariableSelector:l=>{let I=l[x];if(d=!!I&&I!=="false",I===void 0)throw new s(`${x} not set in env, checking config file next.`,{logger:e.logger});return d},configFileSelector:l=>{let I=l[F];return c=!!I&&I!=="false",c},default:!1},{profile:o})();if(e.ec2MetadataV1Disabled||U){let l=[];throw e.ec2MetadataV1Disabled&&l.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"),c&&l.push(`config file profile (${F})`),d&&l.push(`process environment variable (${x})`),new v(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${l.join(", ")}].`)}}let V=(await A(async()=>{let c;try{c=await ne(E)}catch(d){throw d.statusCode===401&&(t=!1),d}return c},i)).trim();return A(async()=>{let c;try{c=await ae(V,E,e)}catch(d){throw d.statusCode===401&&(t=!1),d}return c},i)};return async()=>{let i=await D();if(t)return n?.debug("AWS SDK Instance Metadata","using v1 fallback (no token fetch)"),f(a,{...i,timeout:r});{let E;try{E=(await re({...i,timeout:r})).toString()}catch(T){if(T?.statusCode===400)throw Object.assign(T,{message:"EC2 Metadata token request returned error"});return(T.message==="TimeoutError"||[403,404,405].includes(T.statusCode))&&(t=!0),n?.debug("AWS SDK Instance Metadata","using v1 fallback (initial)"),f(a,{...i,timeout:r})}return f(a,{...i,headers:{[L]:E},timeout:r})}}},re=async e=>m({...e,path:te,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}}),ne=async e=>(await m({...e,path:k})).toString(),ae=async(e,t,n)=>{let o=JSON.parse((await m({...t,path:k+e})).toString());if(!N(o))throw new s("Invalid response received from instance metadata service.",{logger:n.logger});return g(o)};export{me as DEFAULT_MAX_RETRIES,pe as DEFAULT_TIMEOUT,y as ENV_CMDS_AUTH_TOKEN,C as ENV_CMDS_FULL_URI,O as ENV_CMDS_RELATIVE_URI,_ as Endpoint,Ne as fromContainerMetadata,Je as fromInstanceMetadata,D as getInstanceMetadataEndpoint,m as httpRequest,h as providerConfigFromInit};
