AWS appconfig medium security documentation change
Summary
Added error handling for expired/corrupted tokens and session restart logic across Java/Python/JavaScript samples
Security assessment
Added explicit handling of EXPIRED/CORRUPTED tokens and session restart logic prevents use of invalid credentials. This addresses potential security risks from stale/compromised tokens being reused.
Diff
diff --git a/appconfig/latest/userguide/appconfig-code-samples-using-API-read-configuration.md b/appconfig/latest/userguide/appconfig-code-samples-using-API-read-configuration.md index fc1c735f1..8fc8f1407 100644 --- a//appconfig/latest/userguide/appconfig-code-samples-using-API-read-configuration.md +++ b//appconfig/latest/userguide/appconfig-code-samples-using-API-read-configuration.md @@ -28 +28,11 @@ Java - class AppConfigApiRetriever { + public class AppConfigApiRetriever { + + /* + * Set of AppConfig invalid parameter problems that require restarting the configuration session. + * If the GetLatestConfiguration API call fails with any of these problems (e.g. token is EXPIRED or CORRUPTED), + * we need to call StartConfigurationSession again to obtain a new configuration token before retrying. + */ + private final Set<InvalidParameterProblem> SESSION_RESTART_REQUIRED = + Stream.of(InvalidParameterProblem.EXPIRED, InvalidParameterProblem.CORRUPTED) + .collect(Collectors.toSet()); + @@ -32 +42 @@ Java - private AppConfigDataClient appConfigData; + private final AppConfigDataClient appConfigData; @@ -58,5 +68 @@ Java - StartConfigurationSessionResponse session = appConfigData.startConfigurationSession(req -> req - .applicationIdentifier("MyDemoApp") - .configurationProfileIdentifier("MyConfig") - .environmentIdentifier("Beta")); - this.configurationToken = session.initialConfigurationToken(); + startNewSession(); @@ -64,0 +71,3 @@ Java + GetLatestConfigurationResponse response = null; + + try { @@ -71,2 +80,37 @@ Java - GetLatestConfigurationResponse response = appConfigData.getLatestConfiguration( - GetLatestConfigurationRequest.builder().configurationToken(this.configurationToken).build()); + response = appConfigData.getLatestConfiguration( + GetLatestConfigurationRequest.builder() + .configurationToken(this.configurationToken) + .build()); + + } catch (ResourceNotFoundException e) { + // Handle resource not found by refreshing the session + System.err.println("Resource not found — refreshing session and retrying..."); + startNewSession(); + response = appConfigData.getLatestConfiguration( + GetLatestConfigurationRequest.builder() + .configurationToken(this.configurationToken) + .build()); + } catch (BadRequestException e) { + // Handle expired or corrupted token by refreshing the session + boolean needsNewSession = Optional.ofNullable(e.details()) + .map(details -> details.invalidParameters() + .values() + .stream() + .anyMatch(val -> SESSION_RESTART_REQUIRED.contains(val.problem()))) + .orElse(false); + if (needsNewSession) { + System.err.println("Configuration token expired or corrupted — refreshing session and retrying..."); + startNewSession(); + response = appConfigData.getLatestConfiguration( + GetLatestConfigurationRequest.builder() + .configurationToken(this.configurationToken) + .build()); + } else { + throw e; // rethrow if it's another kind of bad request + } + } + + if (response == null) { + // Should not happen, but return cached config if no response + return this.configuration; + } @@ -86 +130 @@ Java - if (configFromApi.asByteArray().length != 0) { + if (configFromApi != null && configFromApi.asByteArray().length != 0) { @@ -88 +132,2 @@ Java - System.out.println("Configuration contents have changed since the last GetLatestConfiguration call, new contents = " + this.configuration.asUtf8String()); + System.out.println("Configuration contents have changed since the last GetLatestConfiguration call, new contents = " + + this.configuration.asUtf8String()); @@ -94,0 +140,10 @@ Java + + /* + Starts a new session with AppConfig and retrieves an initial configuration token. + */ + private void startNewSession() { + StartConfigurationSessionResponse session = appConfigData.startConfigurationSession(req -> req + .applicationIdentifier("MyDemoApp") + .configurationProfileIdentifier("MyConfig") + .environmentIdentifier("Beta")); + this.configurationToken = session.initialConfigurationToken(); @@ -95,0 +151,2 @@ Java + } + @@ -107,0 +165,5 @@ Python + # Set of AppConfig invalid parameter problems that require restarting the configuration session. + # If the GetLatestConfiguration API call fails with any of these problems (e.g. token is EXPIRED or CORRUPTED), + # we need to call StartConfigurationSession again to obtain a new configuration token before retrying. + SESSION_RESTART_REQUIRED = {"EXPIRED", "CORRUPTED"} + @@ -124,6 +186 @@ Python - session = self.appconfigdata.start_configuration_session( - ApplicationIdentifier='MyDemoApp', - ConfigurationProfileIdentifier='MyConfig', - EnvironmentIdentifier='Beta' - ) - self.configuration_token = session['InitialConfigurationToken'] + self._start_new_session() @@ -130,0 +188,2 @@ Python + response = None + try: @@ -135 +194,34 @@ Python - response = self.appconfigdata.get_latest_configuration(ConfigurationToken=self.configuration_token) + response = self.appconfigdata.get_latest_configuration( + ConfigurationToken=self.configuration_token + ) + except ClientError as e: + error_code = e.response.get("Error", {}).get("Code") + # ResourceNotFoundException — usually means the token/session is invalid or expired + if error_code == "ResourceNotFoundException": + print("Resource not found — refreshing session and retrying...") + self._start_new_session() + response = self.appconfigdata.get_latest_configuration( + ConfigurationToken=self.configuration_token + ) + # BadRequestException — check if it's expired or corrupted token + elif error_code == "BadRequestException": + details = e.response.get("Error", {}).get("Details", {}) or {} + invalid_params = details.get("InvalidParameters", {}) or {} + needs_new_session = any( + param.get("Problem") in self.SESSION_RESTART_REQUIRED + for param in invalid_params.values() + ) + if needs_new_session: + print("Configuration token expired or corrupted — refreshing session and retrying...") + self._start_new_session() + response = self.appconfigdata.get_latest_configuration( + ConfigurationToken=self.configuration_token + ) + else: + raise + else: + raise + + if response is None: + # Should not happen, but return cached config if no response + return self.configuration @@ -144 +236,3 @@ Python - config_from_api = response['Configuration'].read() + config_stream = response.get('Configuration') + if config_stream: + config_from_api = config_stream.read() @@ -147 +241,4 @@ Python - print('Configuration contents have changed since the last GetLatestConfiguration call, new contents = ' + str(self.configuration)) + print( + 'Configuration contents have changed since the last GetLatestConfiguration call, new contents = ' + + self.configuration.decode('utf-8', errors='ignore') + ) @@ -152,0 +250,9 @@ Python + # Starts a new session with AppConfig and retrieves an initial configuration token. + def _start_new_session(self): + session = self.appconfigdata.start_configuration_session( + ApplicationIdentifier='MyDemoApp', + ConfigurationProfileIdentifier='MyConfig', + EnvironmentIdentifier='Beta' + ) + self.configuration_token = session['InitialConfigurationToken'] + @@ -159 +265,2 @@ JavaScript - For more information about these APIs, see [AWS AppConfig Data](https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_Operations_AWS_AppConfig_Data.html). + For more information about these APIs, see [AWS AppConfig Data](https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/API_Operations_AWS_AppConfig_Data.html) + . @@ -182,0 +290 @@ JavaScript + async startSession() { @@ -184 +292 @@ JavaScript - Returns the latest configuration data stored in AWS AppConfig. + Starts a new session with the StartConfigurationSession API to get an initial configuration token. @@ -186,7 +293,0 @@ JavaScript - async getConfig() { - /* - If there is no configuration token yet, get one by starting a new session with the StartConfigurationSession API. - Note that this API does not return configuration data. Rather, it returns an initial configuration token that is - subsequently passed to the GetLatestConfiguration API. - */ - if (!this.configurationToken) { @@ -202,0 +304,15 @@ JavaScript + /* + Returns the latest configuration data stored in AWS AppConfig. + */ + async getConfig() { + /* + If there is no configuration token yet, get one by starting a new session with the StartConfigurationSession API. + Note that this API does not return configuration data. Rather, it returns an initial configuration token that is + subsequently passed to the GetLatestConfiguration API. + */ + if (!this.configurationToken) { + await this.startSession(); + } + + let response; + try { @@ -209 +325 @@ JavaScript