MediaWiki  master
ApiCSPReport Class Reference

Api module to receive and log CSP violation reports. More...

Inheritance diagram for ApiCSPReport:
Collaboration diagram for ApiCSPReport:

Public Member Functions

 execute ()
 Logs a content-security-policy violation report from web browser. More...
 
 getAllowedParams ()
 Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (array with PARAM_* constants as keys) Don't call this function directly: use getFinalParams() to allow hooks to modify parameters as needed. More...
 
 isInternal ()
 Mark as internal. More...
 
 isReadMode ()
 Even if you don't have read rights, we still want your report. More...
 
 mustBePosted ()
 Indicates whether this module must be called with a POST request. More...
 
 shouldCheckMaxLag ()
 Doesn't touch db, so max lag should be rather irrelavent. More...
 
- Public Member Functions inherited from ApiBase
 __construct (ApiMain $mainModule, $moduleName, $modulePrefix='')
 
 getModuleManager ()
 Get the module manager, or null if this module has no sub-modules. More...
 
 getCustomPrinter ()
 If the module may only be used with a certain format module, it should override this method to return an instance of that formatter. More...
 
 getHelpUrls ()
 Return links to more detailed help pages about the module. More...
 
 shouldCheckMaxlag ()
 Indicates if this module needs maxlag to be checked. More...
 
 isWriteMode ()
 Indicates whether this module requires write mode. More...
 
 isDeprecated ()
 Indicates whether this module is deprecated. More...
 
 needsToken ()
 Returns the token type this module requires in order to execute. More...
 
 getConditionalRequestData ( $condition)
 Returns data for HTTP conditional request mechanisms. More...
 
 getModuleName ()
 Get the name of the module being executed by this instance. More...
 
 getModulePrefix ()
 Get parameter prefix (usually two letters or an empty string). More...
 
 getMain ()
 Get the main module. More...
 
 isMain ()
 Returns true if this module is the main module ($this === $this->mMainModule), false otherwise. More...
 
 getParent ()
 Get the parent of this module. More...
 
 lacksSameOriginSecurity ()
 Returns true if the current request breaks the same-origin policy. More...
 
 getModulePath ()
 Get the path to this module. More...
 
 getModuleFromPath ( $path)
 Get a module from its module path. More...
 
 getResult ()
 Get the result object. More...
 
 getErrorFormatter ()
 
 getContinuationManager ()
 
 setContinuationManager (ApiContinuationManager $manager=null)
 
 dynamicParameterDocumentation ()
 Indicate if the module supports dynamically-determined parameters that cannot be included in self::getAllowedParams(). More...
 
 encodeParamName ( $paramName)
 This method mangles parameter name based on the prefix supplied to the constructor. More...
 
 extractRequestParams ( $options=[])
 Using getAllowedParams(), this function makes an array of the values provided by the user, with key being the name of the variable, and value - validated value from user or default. More...
 
 requireOnlyOneParameter ( $params,... $required)
 Die if none or more than one of a certain set of parameters is set and not false. More...
 
 requireMaxOneParameter ( $params,... $required)
 Die if more than one of a certain set of parameters is set and not false. More...
 
 requireAtLeastOneParameter ( $params,... $required)
 Die if none of a certain set of parameters is set and not false. More...
 
 requirePostedParameters ( $params, $prefix='prefix')
 Die if any of the specified parameters were found in the query part of the URL rather than the post body. More...
 
 getTitleOrPageId ( $params, $load=false)
 Get a WikiPage object from a title or pageid param, if possible. More...
 
 getTitleFromTitleOrPageId ( $params)
 Get a Title object from a title or pageid param, if possible. More...
 
 handleParamNormalization ( $paramName, $value, $rawValue)
 Handle when a parameter was Unicode-normalized. More...
 
 validateToken ( $token, array $params)
 Validate the supplied token. More...
 
 getWatchlistUser ( $params)
 Gets the user for whom to get the watchlist. More...
 
 errorArrayToStatus (array $errors, User $user=null)
 Turn an array of message keys or key+param arrays into a Status. More...
 
 addBlockInfoToStatus (StatusValue $status, Authority $user=null)
 Add block info to block messages in a Status. More...
 
 addWarning ( $msg, $code=null, $data=null)
 Add a warning for this module. More...
 
 addDeprecation ( $msg, $feature, $data=[])
 Add a deprecation warning for this module. More...
 
 addError ( $msg, $code=null, $data=null)
 Add an error for this module without aborting. More...
 
 addMessagesFromStatus (StatusValue $status, $types=[ 'warning', 'error'], array $filter=[])
 Add warnings and/or errors from a Status. More...
 
 dieWithError ( $msg, $code=null, $data=null, $httpCode=null)
 Abort execution with an error. More...
 
 dieWithException (Throwable $exception, array $options=[])
 Abort execution with an error derived from a throwable. More...
 
 dieBlocked (Block $block)
 Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die with an error message including block info. More...
 
 dieStatus (StatusValue $status)
 Throw an ApiUsageException based on the Status object. More...
 
 dieReadOnly ()
 Helper function for readonly errors. More...
 
 checkUserRightsAny ( $rights, $user=null)
 Helper function for permission-denied errors. More...
 
 checkTitleUserPermissions ( $pageIdentity, $actions, array $options=[])
 Helper function for permission-denied errors. More...
 
 dieWithErrorOrDebug ( $msg, $code=null, $data=null, $httpCode=null)
 Will only set a warning instead of failing if the global $wgDebugAPI is set to true. More...
 
 logFeatureUsage ( $feature)
 Write logging information for API features to a debug log, for usage analysis. More...
 
 getFinalSummary ()
 Get final module summary. More...
 
 getFinalDescription ()
 Get final module description, after hooks have had a chance to tweak it as needed. More...
 
 getFinalParams ( $flags=0)
 Get final list of parameters, after hooks have had a chance to tweak it as needed. More...
 
 getFinalParamDescription ()
 Get final parameter descriptions, after hooks have had a chance to tweak it as needed. More...
 
 modifyHelp (array &$help, array $options, array &$tocData)
 Called from ApiHelp before the pieces are joined together and returned. More...
 
- Public Member Functions inherited from ContextSource
 canUseWikiPage ()
 Check whether a WikiPage object can be get with getWikiPage(). More...
 
 exportSession ()
 Export the resolved user IP, HTTP headers, user ID, and session ID. More...
 
 getAuthority ()
 
 getConfig ()
 
 getContext ()
 Get the base IContextSource object. More...
 
 getCsrfTokenSet ()
 Get a repository to obtain and match CSRF tokens. More...
 
 getLanguage ()
 
 getOutput ()
 
 getRequest ()
 
 getSkin ()
 
 getStats ()
 
 getTiming ()
 
 getTitle ()
 
 getUser ()
 
 getWikiPage ()
 Get the WikiPage object. More...
 
 msg ( $key,... $params)
 Get a Message object with context set Parameters are the same as wfMessage() More...
 
 setContext (IContextSource $context)
 

Private Member Functions

 error ( $code, $method)
 Stop processing the request, and output/log an error. More...
 
 generateLogLine ( $flags, $report)
 Get text of log line. More...
 
 getFlags ( $report, $userAgent)
 Get extra notes about the report. More...
 
 getReport ()
 Get the report from post body and turn into associative array. More...
 
 logReport ( $flags, $logLine, $context)
 Log CSP report, with a different severity depending on $flags. More...
 
 matchUrlPattern ( $url, array $patterns)
 
 originFromUrl ( $url)
 
 verifyPostBodyOk ()
 Output an api error if post body is obviously not OK. More...
 

Private Attributes

LoggerInterface $log
 
const MAX_POST_SIZE = 8192
 These reports should be small. More...
 

Additional Inherited Members

- Static Public Member Functions inherited from ApiBase
static makeMessage ( $msg, IContextSource $context, array $params=null)
 Create a Message from a string or array. More...
 
- Public Attributes inherited from ApiBase
const PARAM_RANGE_ENFORCE = 'api-param-range-enforce'
 (boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE More...
 
const PARAM_DFLT = ParamValidator::PARAM_DEFAULT
 
const PARAM_ISMULTI = ParamValidator::PARAM_ISMULTI
 
const PARAM_TYPE = ParamValidator::PARAM_TYPE
 
const PARAM_MAX = IntegerDef::PARAM_MAX
 
const PARAM_MAX2 = IntegerDef::PARAM_MAX2
 
const PARAM_MIN = IntegerDef::PARAM_MIN
 
const PARAM_ALLOW_DUPLICATES = ParamValidator::PARAM_ALLOW_DUPLICATES
 
const PARAM_DEPRECATED = ParamValidator::PARAM_DEPRECATED
 
const PARAM_REQUIRED = ParamValidator::PARAM_REQUIRED
 
const PARAM_SUBMODULE_MAP = SubmoduleDef::PARAM_SUBMODULE_MAP
 
const PARAM_SUBMODULE_PARAM_PREFIX = SubmoduleDef::PARAM_SUBMODULE_PARAM_PREFIX
 
const PARAM_ALL = ParamValidator::PARAM_ALL
 
const PARAM_EXTRA_NAMESPACES = NamespaceDef::PARAM_EXTRA_NAMESPACES
 
const PARAM_SENSITIVE = ParamValidator::PARAM_SENSITIVE
 
const PARAM_DEPRECATED_VALUES = EnumDef::PARAM_DEPRECATED_VALUES
 
const PARAM_ISMULTI_LIMIT1 = ParamValidator::PARAM_ISMULTI_LIMIT1
 
const PARAM_ISMULTI_LIMIT2 = ParamValidator::PARAM_ISMULTI_LIMIT2
 
const PARAM_MAX_BYTES = StringDef::PARAM_MAX_BYTES
 
const PARAM_MAX_CHARS = StringDef::PARAM_MAX_CHARS
 
const PARAM_HELP_MSG = 'api-param-help-msg'
 (string|array|Message) Specify an alternative i18n documentation message for this parameter. More...
 
const PARAM_HELP_MSG_APPEND = 'api-param-help-msg-append'
 ((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this parameter. More...
 
const PARAM_HELP_MSG_INFO = 'api-param-help-msg-info'
 (array) Specify additional information tags for the parameter. More...
 
const PARAM_VALUE_LINKS = 'api-param-value-links'
 Deprecated and unused. More...
 
const PARAM_HELP_MSG_PER_VALUE = 'api-param-help-msg-per-value'
 ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg for ApiBase::makeMessage(). More...
 
const PARAM_TEMPLATE_VARS = 'param-template-vars'
 (array) Indicate that this is a templated parameter, and specify replacements. More...
 
const ALL_DEFAULT_STRING = '*'
 (string|array|Message) Specify an alternative i18n documentation message for this parameter. More...
 
const LIMIT_BIG1 = 500
 Fast query, standard limit. More...
 
const LIMIT_BIG2 = 5000
 Fast query, apihighlimits limit. More...
 
const LIMIT_SML1 = 50
 Slow query, standard limit. More...
 
const LIMIT_SML2 = 500
 Slow query, apihighlimits limit. More...
 
const GET_VALUES_FOR_HELP = 1
 getAllowedParams() flag: When set, the result could take longer to generate, but should be more thorough. More...
 
string $mModulePrefix
 (string|array|Message) Specify an alternative i18n documentation message for this parameter. More...
 
- Protected Member Functions inherited from ApiBase
 getExamplesMessages ()
 Returns usage examples for this module. More...
 
 getWebUITokenSalt (array $params)
 Fetch the salt used in the Web UI corresponding to this module. More...
 
 getDB ()
 Gets a default replica DB connection object. More...
 
 getPermissionManager ()
 Obtain a PermissionManager instance that subclasses may use in their authorization checks. More...
 
 getHookContainer ()
 Get a HookContainer, for running extension hooks or for hook metadata. More...
 
 getHookRunner ()
 Get an ApiHookRunner for running core API hooks. More...
 
 getParameter ( $paramName, $parseLimit=true)
 Get a value for the given parameter. More...
 
 getParameterFromSettings ( $name, $settings, $parseLimit)
 Using the settings determine the value for the given parameter. More...
 
 useTransactionalTimeLimit ()
 Call wfTransactionalTimeLimit() if this request was POSTed. More...
 
 filterIDs ( $fields, array $ids)
 Filter out-of-range values from a list of positive integer IDs. More...
 
 dieContinueUsageIf ( $condition)
 Die with the 'badcontinue' error. More...
 
 getSummaryMessage ()
 Return the summary message. More...
 
 getExtendedDescription ()
 Return the extended help text message. More...
 
 getHelpFlags ()
 Generates the list of flags for the help screen and for action=paraminfo. More...
 
 getModuleSourceInfo ()
 Returns information about the source of this module, if known. More...
 
- Static Protected Member Functions inherited from ApiBase
static dieDebug ( $method, $message)
 Internal code errors should be reported with this method. More...
 

Detailed Description

Api module to receive and log CSP violation reports.

Definition at line 31 of file ApiCSPReport.php.

Member Function Documentation

◆ error()

ApiCSPReport::error (   $code,
  $method 
)
private

Stop processing the request, and output/log an error.

Parameters
string$codeerror code
string$methodmethod that made error
Exceptions
ApiUsageExceptionAlways

Definition at line 247 of file ApiCSPReport.php.

References ApiBase\dieWithError(), ContextSource\getRequest(), and wfEscapeWikiText().

Referenced by getReport(), and verifyPostBodyOk().

◆ execute()

ApiCSPReport::execute ( )

Logs a content-security-policy violation report from web browser.

Reimplemented from ApiBase.

Definition at line 44 of file ApiCSPReport.php.

References generateLogLine(), getFlags(), ApiBase\getModuleName(), ApiBase\getParameter(), getReport(), ContextSource\getRequest(), ApiBase\getResult(), ContextSource\getUser(), logReport(), and verifyPostBodyOk().

◆ generateLogLine()

ApiCSPReport::generateLogLine (   $flags,
  $report 
)
private

Get text of log line.

Parameters
array$flagsof additional markers for this report
array$reportthe csp report
Returns
string Text to put in log

Definition at line 208 of file ApiCSPReport.php.

References $line, and originFromUrl().

Referenced by execute().

◆ getAllowedParams()

ApiCSPReport::getAllowedParams ( )

Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (array with PARAM_* constants as keys) Don't call this function directly: use getFinalParams() to allow hooks to modify parameters as needed.

Some derived classes may choose to handle an integer $flags parameter in the overriding methods. Callers of this method can pass zero or more OR-ed flags like GET_VALUES_FOR_HELP.

Stability: stable
to override
Returns
array

Reimplemented from ApiBase.

Definition at line 258 of file ApiCSPReport.php.

References ApiBase\PARAM_DFLT, ApiBase\PARAM_REQUIRED, and ApiBase\PARAM_TYPE.

◆ getFlags()

ApiCSPReport::getFlags (   $report,
  $userAgent 
)
private

Get extra notes about the report.

Parameters
array$reportThe CSP report
string$userAgent
Returns
array

Definition at line 89 of file ApiCSPReport.php.

References $source, ContentSecurityPolicy\falsePositiveBrowser(), ContextSource\getConfig(), ApiBase\getParameter(), and matchUrlPattern().

Referenced by execute().

◆ getReport()

ApiCSPReport::getReport ( )
private

Get the report from post body and turn into associative array.

Returns
array

Definition at line 178 of file ApiCSPReport.php.

References error(), FormatJson\FORCE_ASSOC, ContextSource\getRequest(), and FormatJson\parse().

Referenced by execute().

◆ isInternal()

ApiCSPReport::isInternal ( )

Mark as internal.

This isn't meant to be used by normal api users

Returns
bool

Reimplemented from ApiBase.

Definition at line 280 of file ApiCSPReport.php.

◆ isReadMode()

ApiCSPReport::isReadMode ( )

Even if you don't have read rights, we still want your report.

Returns
bool

Reimplemented from ApiBase.

Definition at line 288 of file ApiCSPReport.php.

◆ logReport()

ApiCSPReport::logReport (   $flags,
  $logLine,
  $context 
)
private

Log CSP report, with a different severity depending on $flags.

Parameters
array$flagsFlags for this report
string$logLinetext of log entry
array$contextlogging context

Definition at line 72 of file ApiCSPReport.php.

References ContextSource\$context.

Referenced by execute().

◆ matchUrlPattern()

ApiCSPReport::matchUrlPattern (   $url,
array  $patterns 
)
private
Parameters
string$url
string[]$patterns
Returns
bool

Definition at line 129 of file ApiCSPReport.php.

References wfAssembleUrl(), and wfParseUrl().

Referenced by getFlags().

◆ mustBePosted()

ApiCSPReport::mustBePosted ( )

Indicates whether this module must be called with a POST request.

Stability: stable
to override
Returns
bool

Reimplemented from ApiBase.

Definition at line 272 of file ApiCSPReport.php.

◆ originFromUrl()

ApiCSPReport::originFromUrl (   $url)
private
Parameters
string$url
Returns
string

Definition at line 231 of file ApiCSPReport.php.

References wfAssembleUrl(), and wfParseUrl().

Referenced by generateLogLine().

◆ shouldCheckMaxLag()

ApiCSPReport::shouldCheckMaxLag ( )

Doesn't touch db, so max lag should be rather irrelavent.

Also, this makes sure that reports aren't lost during lag events.

Returns
bool

Definition at line 298 of file ApiCSPReport.php.

◆ verifyPostBodyOk()

ApiCSPReport::verifyPostBodyOk ( )
private

Output an api error if post body is obviously not OK.

Definition at line 160 of file ApiCSPReport.php.

References error(), and ContextSource\getRequest().

Referenced by execute().

Member Data Documentation

◆ $log

LoggerInterface ApiCSPReport::$log
private

Definition at line 34 of file ApiCSPReport.php.

◆ MAX_POST_SIZE

const ApiCSPReport::MAX_POST_SIZE = 8192
private

These reports should be small.

Ignore super big reports out of paranoia

Definition at line 39 of file ApiCSPReport.php.


The documentation for this class was generated from the following file: