|
| 1 | +package tfapstra |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/Juniper/apstra-go-sdk/apstra" |
| 10 | + "github.com/Juniper/terraform-provider-apstra/apstra/authentication" |
| 11 | + "github.com/Juniper/terraform-provider-apstra/apstra/private" |
| 12 | + "github.com/hashicorp/terraform-plugin-framework/ephemeral" |
| 13 | + "github.com/hashicorp/terraform-plugin-framework/ephemeral/schema" |
| 14 | +) |
| 15 | + |
| 16 | +var ( |
| 17 | + _ ephemeral.EphemeralResource = (*ephemeralToken)(nil) |
| 18 | + _ ephemeral.EphemeralResourceWithClose = (*ephemeralToken)(nil) |
| 19 | + _ ephemeral.EphemeralResourceWithConfigure = (*ephemeralToken)(nil) |
| 20 | + _ ephemeral.EphemeralResourceWithRenew = (*ephemeralToken)(nil) |
| 21 | + _ ephemeralWithSetClient = (*ephemeralToken)(nil) |
| 22 | +) |
| 23 | + |
| 24 | +type ephemeralToken struct { |
| 25 | + client *apstra.Client |
| 26 | +} |
| 27 | + |
| 28 | +func (o *ephemeralToken) Metadata(_ context.Context, req ephemeral.MetadataRequest, resp *ephemeral.MetadataResponse) { |
| 29 | + resp.TypeName = req.ProviderTypeName + "_api_token" |
| 30 | +} |
| 31 | + |
| 32 | +func (o *ephemeralToken) Schema(_ context.Context, _ ephemeral.SchemaRequest, resp *ephemeral.SchemaResponse) { |
| 33 | + resp.Schema = schema.Schema{ |
| 34 | + MarkdownDescription: docCategoryAuthentication + "This Ephemeral Resource retrieves a unique API token and (optionally) invalidates it on Close.", |
| 35 | + Attributes: authentication.ApiToken{}.EphemeralAttributes(), |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +func (o *ephemeralToken) Configure(ctx context.Context, req ephemeral.ConfigureRequest, resp *ephemeral.ConfigureResponse) { |
| 40 | + configureEphemeral(ctx, o, req, resp) |
| 41 | +} |
| 42 | + |
| 43 | +func (o *ephemeralToken) Open(ctx context.Context, req ephemeral.OpenRequest, resp *ephemeral.OpenResponse) { |
| 44 | + var config authentication.ApiToken |
| 45 | + resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) |
| 46 | + if resp.Diagnostics.HasError() { |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + // set default values |
| 51 | + config.SetDefaults() |
| 52 | + |
| 53 | + // create a new client using the credentials in the embedded client's config |
| 54 | + client, err := o.client.Config().NewClient(ctx) |
| 55 | + if err != nil { |
| 56 | + resp.Diagnostics.AddError("error creating new client", err.Error()) |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + // log in so that the new client fetches an API token |
| 61 | + err = client.Login(ctx) |
| 62 | + if err != nil { |
| 63 | + resp.Diagnostics.AddError("error logging in new client", err.Error()) |
| 64 | + return |
| 65 | + } |
| 66 | + |
| 67 | + // extract the token |
| 68 | + token := client.GetApiToken() |
| 69 | + if token == "" { |
| 70 | + resp.Diagnostics.AddError("requested API token is empty", "requested API token is empty") |
| 71 | + return |
| 72 | + } |
| 73 | + |
| 74 | + // Destroy the new client without invalidating the API token we just collected. |
| 75 | + // We call Logout() here only for the side effect of stopping the task monitor |
| 76 | + // goroutine. This client *can't* invalidate the session because it no longer |
| 77 | + // has an API token. |
| 78 | + client.SetApiToken("") |
| 79 | + err = client.Logout(ctx) |
| 80 | + if err != nil { |
| 81 | + resp.Diagnostics.AddError("error logging out client", err.Error()) |
| 82 | + return |
| 83 | + } |
| 84 | + |
| 85 | + config.LoadApiData(ctx, token, &resp.Diagnostics) |
| 86 | + if resp.Diagnostics.HasError() { |
| 87 | + return |
| 88 | + } |
| 89 | + |
| 90 | + // sanity check the token lifetime |
| 91 | + now := time.Now() |
| 92 | + if now.After(config.ExpiresAt) { |
| 93 | + resp.Diagnostics.AddError( |
| 94 | + "Just-fetched API token is expired", |
| 95 | + fmt.Sprintf("Token expired at: %s. Current time is: %s", config.ExpiresAt, now), |
| 96 | + ) |
| 97 | + return |
| 98 | + } |
| 99 | + |
| 100 | + // warn the user about imminent expiration |
| 101 | + warn := time.Duration(config.WarnSeconds.ValueInt64()) * time.Second |
| 102 | + if now.Add(warn).After(config.ExpiresAt) { |
| 103 | + resp.Diagnostics.AddWarning( |
| 104 | + fmt.Sprintf("API token expires within %d second warning threshold", config.WarnSeconds), |
| 105 | + fmt.Sprintf("API token expires at %s. Current time: %s", config.ExpiresAt, now), |
| 106 | + ) |
| 107 | + } |
| 108 | + |
| 109 | + // save the private state |
| 110 | + config.SetPrivateState(ctx, resp.Private, &resp.Diagnostics) |
| 111 | + if resp.Diagnostics.HasError() { |
| 112 | + return |
| 113 | + } |
| 114 | + |
| 115 | + // set the renew timestamp to the early warning time |
| 116 | + resp.RenewAt = config.ExpiresAt.Add(-1 * warn) |
| 117 | + |
| 118 | + // set the result |
| 119 | + resp.Diagnostics.Append(resp.Result.Set(ctx, &config)...) |
| 120 | +} |
| 121 | + |
| 122 | +func (o *ephemeralToken) Renew(ctx context.Context, req ephemeral.RenewRequest, resp *ephemeral.RenewResponse) { |
| 123 | + var privateEphemeralApiToken private.EphemeralApiToken |
| 124 | + privateEphemeralApiToken.LoadPrivateState(ctx, req.Private, &resp.Diagnostics) |
| 125 | + if resp.Diagnostics.HasError() { |
| 126 | + return |
| 127 | + } |
| 128 | + |
| 129 | + now := time.Now() |
| 130 | + if now.After(privateEphemeralApiToken.ExpiresAt) { |
| 131 | + resp.Diagnostics.AddError( |
| 132 | + "API token has expired", |
| 133 | + fmt.Sprintf("Token expired at: %s. Current time is: %s", privateEphemeralApiToken.ExpiresAt, now), |
| 134 | + ) |
| 135 | + return |
| 136 | + } |
| 137 | + |
| 138 | + if now.Add(privateEphemeralApiToken.WarnThreshold).After(privateEphemeralApiToken.ExpiresAt) { |
| 139 | + resp.Diagnostics.AddWarning( |
| 140 | + fmt.Sprintf("API token expires within %d second warning threshold", privateEphemeralApiToken.WarnThreshold), |
| 141 | + fmt.Sprintf("API token expires at %s. Current time: %s", privateEphemeralApiToken.ExpiresAt, now), |
| 142 | + ) |
| 143 | + } |
| 144 | + |
| 145 | + // set the renew timestamp to the expiration time |
| 146 | + resp.RenewAt = privateEphemeralApiToken.ExpiresAt |
| 147 | +} |
| 148 | + |
| 149 | +func (o *ephemeralToken) Close(ctx context.Context, req ephemeral.CloseRequest, resp *ephemeral.CloseResponse) { |
| 150 | + // extract the private state data |
| 151 | + var privateEphemeralApiToken private.EphemeralApiToken |
| 152 | + privateEphemeralApiToken.LoadPrivateState(ctx, req.Private, &resp.Diagnostics) |
| 153 | + |
| 154 | + if privateEphemeralApiToken.DoNotLogOut { |
| 155 | + return // user doesn't want the token invalidated, so there's nothing to do |
| 156 | + } |
| 157 | + |
| 158 | + if time.Now().After(privateEphemeralApiToken.ExpiresAt) { |
| 159 | + return // token has already expired, so there's nothing to do |
| 160 | + } |
| 161 | + |
| 162 | + // create a new client based on the embedded client's config |
| 163 | + client, err := o.client.Config().NewClient(ctx) |
| 164 | + if err != nil { |
| 165 | + resp.Diagnostics.AddError("error creating new client", err.Error()) |
| 166 | + return |
| 167 | + } |
| 168 | + |
| 169 | + // copy the API token from private state into the new client |
| 170 | + client.SetApiToken(privateEphemeralApiToken.Token) |
| 171 | + |
| 172 | + // log out the client using the swapped-in token |
| 173 | + err = client.Logout(ctx) |
| 174 | + if err != nil { |
| 175 | + var ace apstra.ClientErr |
| 176 | + if errors.As(err, &ace) && ace.Type() == apstra.ErrAuthFail { |
| 177 | + return // 401 is okay |
| 178 | + } |
| 179 | + |
| 180 | + resp.Diagnostics.AddError("Error while logging out the API key", err.Error()) |
| 181 | + return |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +func (o *ephemeralToken) setClient(client *apstra.Client) { |
| 186 | + o.client = client |
| 187 | +} |
0 commit comments