code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
public void executeNSU() throws Exception {
final DeferredGroupException dge = mock(DeferredGroupException.class);
when(dge.getCause()).thenReturn(new NoSuchUniqueName("foo", "metrics"));
when(query_result.configureFromQuery((TSQuery)any(), anyInt()))
.thenReturn(Deferred.fromError(dge));
final HttpQuery query = NettyMocks.getQuery(tsdb,
"/api/query?start=1h-ago&m=sum:sys.cpu.user");
rpc.execute(tsdb, query);
assertEquals(HttpResponseStatus.BAD_REQUEST, query.response().getStatus());
final String json =
query.response().getContent().toString(Charset.forName("UTF-8"));
assertTrue(json.contains("No such name for 'foo': 'metrics'"));
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
public void postQueryNoMetricBadRequest() throws Exception {
final DeferredGroupException dge = mock(DeferredGroupException.class);
when(dge.getCause()).thenReturn(new NoSuchUniqueName("foo", "metrics"));
when(query_result.configureFromQuery((TSQuery)any(), anyInt()))
.thenReturn(Deferred.fromError(dge));
HttpQuery query = NettyMocks.postQuery(tsdb, "/api/query",
"{\"start\":1425440315306,\"queries\":" +
"[{\"metric\":\"nonexistent\",\"aggregator\":\"sum\",\"rate\":true," +
"\"rateOptions\":{\"counter\":false}}]}");
rpc.execute(tsdb, query);
assertEquals(HttpResponseStatus.BAD_REQUEST, query.response().getStatus());
final String json =
query.response().getContent().toString(Charset.forName("UTF-8"));
assertTrue(json.contains("No such name for 'foo': 'metrics'"));
} | 1 | Java | CWE-74 | Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') | The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/74.html | safe |
protected boolean validateIssuerAudienceAndAzp(@NonNull JwtClaims claims,
@NonNull String iss,
@NonNull List<String> audiences,
@NonNull String clientId,
@NonNull OpenIdClientConfiguration openIdClientConfiguration) {
if (openIdClientConfiguration.getIssuer().isPresent()) {
Optional<URL> issuerOptional = openIdClientConfiguration.getIssuer();
if (issuerOptional.isPresent()) {
String issuer = issuerOptional.get().toString();
return issuer.equalsIgnoreCase(iss) &&
audiences.contains(clientId) &&
validateAzp(claims, clientId, audiences);
}
}
return false;
} | 1 | Java | CWE-284 | Improper Access Control | The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor. | https://cwe.mitre.org/data/definitions/284.html | safe |
public static Config setComments(Config config, String path, List<String> comments) {
return config.withValue(path, setComments(config.getValue(path), comments));
} | 1 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
public static ConfigValue setComments(ConfigValue value, List<String> comments) {
if (value.origin() instanceof SimpleConfigOrigin && value instanceof AbstractConfigValue) {
return ((AbstractConfigValue) value).withOrigin(
((SimpleConfigOrigin) value.origin()).setComments(comments)
);
} else {
return value;
}
} | 1 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
private OpenComputersConfigCommentManipulationHook() {
} | 1 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
public boolean matches(InetAddress address) {
byte[] entry = address.getAddress();
if (entry.length != min.length) return false;
for (int i = 0; i < entry.length; i++) {
int value = 0xFF & entry[i];
if (value < (0xFF & min[i]) || value > (0xFF & max[i])) return false;
}
return true;
} | 1 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
public static InetAddressRange parse(String addressStr, String prefixSizeStr) {
int prefixSize;
try {
prefixSize = Integer.parseInt(prefixSizeStr);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(String.format("Malformed address range entry '%s': Cannot extract size of CIDR mask from '%s'.",
addressStr + '/' + prefixSizeStr, prefixSizeStr));
}
InetAddress address;
try {
address = InetAddresses.forString(addressStr);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(String.format("Malformed address range entry '%s': Cannot extract IP address from '%s'.",
addressStr + '/' + prefixSizeStr, addressStr));
}
// Mask the bytes of the IP address.
byte[] minBytes = address.getAddress(), maxBytes = address.getAddress();
int size = prefixSize;
for (int i = 0; i < minBytes.length; i++) {
if (size <= 0) {
minBytes[i] = (byte) 0;
maxBytes[i] = (byte) 0xFF;
} else if (size < 8) {
minBytes[i] = (byte) (minBytes[i] & 0xFF << (8 - size));
maxBytes[i] = (byte) (maxBytes[i] | ~(0xFF << (8 - size)));
}
size -= 8;
}
return new InetAddressRange(minBytes, maxBytes);
} | 1 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
InetAddressRange(byte[] min, byte[] max) {
this.min = min;
this.max = max;
} | 1 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
public boolean matches(InetAddress socketAddress) {
return
socketAddress.isAnyLocalAddress() // 0.0.0.0, ::0
|| socketAddress.isLoopbackAddress() // 127.0.0.0/8, ::1
|| socketAddress.isLinkLocalAddress() // 169.254.0.0/16, fe80::/10
|| socketAddress.isSiteLocalAddress() // 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fec0::/10
|| socketAddress.isMulticastAddress() // 224.0.0.0/4, ff00::/8
|| isUniqueLocalAddress(socketAddress) // fd00::/8
|| additionalAddresses.contains(socketAddress);
} | 1 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
private boolean isUniqueLocalAddress(InetAddress address) {
// ULA is actually defined as fc00::/7 (so both fc00::/8 and fd00::/8). However, only the latter is actually
// defined right now, so let's be conservative.
return address instanceof Inet6Address && (address.getAddress()[0] & 0xff) == 0xfd;
} | 1 | Java | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
void testSymlinkTar() throws Exception {
TarArchiver archiver = (TarArchiver) lookup(Archiver.class, "tar");
archiver.setLongfile(TarLongFileMode.posix);
File dummyContent = getTestFile("src/test/resources/symlinks/src");
archiver.addDirectory(dummyContent);
final File archiveFile = new File("target/output/symlinks.tar");
archiver.setDestFile(archiveFile);
archiver.createArchive();
File output = getTestFile("target/output/untaredSymlinks");
output.mkdirs();
TarUnArchiver unarchiver = (TarUnArchiver) lookup(UnArchiver.class, "tar");
unarchiver.setSourceFile(archiveFile);
unarchiver.setDestFile(output);
unarchiver.extract();
// second unpacking should also work
unarchiver.extract();
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
void testSymlinkTar() throws Exception {
TarArchiver archiver = (TarArchiver) lookup(Archiver.class, "tar");
archiver.setLongfile(TarLongFileMode.posix);
File dummyContent = getTestFile("src/test/resources/symlinks/src");
archiver.addDirectory(dummyContent);
final File archiveFile = new File("target/output/symlinks.tar");
archiver.setDestFile(archiveFile);
archiver.createArchive();
File output = getTestFile("target/output/untaredSymlinks");
output.mkdirs();
TarUnArchiver unarchiver = (TarUnArchiver) lookup(UnArchiver.class, "tar");
unarchiver.setSourceFile(archiveFile);
unarchiver.setDestFile(output);
unarchiver.extract();
// second unpacking should also work
unarchiver.extract();
} | 1 | Java | CWE-61 | UNIX Symbolic Link (Symlink) Following | The product, when opening a file or directory, does not sufficiently account for when the file is a symbolic link that resolves to a target outside of the intended control sphere. This could allow an attacker to cause the product to operate on unauthorized files. | https://cwe.mitre.org/data/definitions/61.html | safe |
void testSymlinkZip() throws Exception {
ZipArchiver archiver = (ZipArchiver) lookup(Archiver.class, "zip");
File dummyContent = getTestFile("src/test/resources/symlinks/src");
archiver.addDirectory(dummyContent);
final File archiveFile = new File("target/output/symlinks.zip");
archiveFile.delete();
archiver.setDestFile(archiveFile);
archiver.createArchive();
File output = getTestFile("target/output/unzippedSymlinks");
output.mkdirs();
ZipUnArchiver unarchiver = (ZipUnArchiver) lookup(UnArchiver.class, "zip");
unarchiver.setSourceFile(archiveFile);
unarchiver.setDestFile(output);
unarchiver.extract();
// second unpacking should also work
unarchiver.extract();
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
void testSymlinkZip() throws Exception {
ZipArchiver archiver = (ZipArchiver) lookup(Archiver.class, "zip");
File dummyContent = getTestFile("src/test/resources/symlinks/src");
archiver.addDirectory(dummyContent);
final File archiveFile = new File("target/output/symlinks.zip");
archiveFile.delete();
archiver.setDestFile(archiveFile);
archiver.createArchive();
File output = getTestFile("target/output/unzippedSymlinks");
output.mkdirs();
ZipUnArchiver unarchiver = (ZipUnArchiver) lookup(UnArchiver.class, "zip");
unarchiver.setSourceFile(archiveFile);
unarchiver.setDestFile(output);
unarchiver.extract();
// second unpacking should also work
unarchiver.extract();
} | 1 | Java | CWE-61 | UNIX Symbolic Link (Symlink) Following | The product, when opening a file or directory, does not sufficiently account for when the file is a symbolic link that resolves to a target outside of the intended control sphere. This could allow an attacker to cause the product to operate on unauthorized files. | https://cwe.mitre.org/data/definitions/61.html | safe |
void testNonExistingSymlink() throws Exception {
File zipFile = new File("src/test/resources/symlinks/non_existing_symlink.zip");
ZipUnArchiver unArchiver = getZipUnArchiver(zipFile);
String tmpdir = Files.createTempDirectory("tmpe_extract").toFile().getAbsolutePath();
unArchiver.setDestDirectory(new File(tmpdir));
ArchiverException exception = assertThrows(ArchiverException.class, unArchiver::extract);
assertEquals("Entry is outside of the target directory (entry1)", exception.getMessage());
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
void testNonExistingSymlink() throws Exception {
File zipFile = new File("src/test/resources/symlinks/non_existing_symlink.zip");
ZipUnArchiver unArchiver = getZipUnArchiver(zipFile);
String tmpdir = Files.createTempDirectory("tmpe_extract").toFile().getAbsolutePath();
unArchiver.setDestDirectory(new File(tmpdir));
ArchiverException exception = assertThrows(ArchiverException.class, unArchiver::extract);
assertEquals("Entry is outside of the target directory (entry1)", exception.getMessage());
} | 1 | Java | CWE-61 | UNIX Symbolic Link (Symlink) Following | The product, when opening a file or directory, does not sufficiently account for when the file is a symbolic link that resolves to a target outside of the intended control sphere. This could allow an attacker to cause the product to operate on unauthorized files. | https://cwe.mitre.org/data/definitions/61.html | safe |
public static Map processResponse(Response samlResponse, String target)
throws SAMLException {
List assertions = null;
SAMLServiceManager.SOAPEntry partnerdest = null;
Subject assertionSubject = null;
// verify the signature
boolean isSignedandValid = verifySignature(samlResponse);
if (!isSignedandValid) {
throw new SAMLException(bundle.getString("invalidResponse"));
}
// check Assertion and get back a Map of relevant data including,
// Subject, SOAPEntry for the partner and the List of Assertions.
Map ssMap = verifyAssertionAndGetSSMap(samlResponse);
if (debug.messageEnabled()) {
debug.message("processResponse: ssMap = " + ssMap);
}
if (ssMap == null) {
throw new SAMLException(bundle.getString("invalidAssertion"));
}
assertionSubject = (com.sun.identity.saml.assertion.Subject)
ssMap.get(SAMLConstants.SUBJECT);
if (assertionSubject == null) {
throw new SAMLException(bundle.getString("nullSubject"));
}
partnerdest = (SAMLServiceManager.SOAPEntry)ssMap
.get(SAMLConstants.SOURCE_SITE_SOAP_ENTRY);
if (partnerdest == null) {
throw new SAMLException(bundle.getString("failedAccountMapping"));
}
assertions = (List)ssMap.get(SAMLConstants.POST_ASSERTION);
Map sessMap = null;
try {
sessMap = getAttributeMap(partnerdest, assertions,
assertionSubject, target);
} catch (Exception se) {
debug.error("SAMLUtils.processResponse :" , se);
throw new SAMLException(
bundle.getString("failProcessResponse"));
}
return sessMap;
} | 1 | Java | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
public static boolean verifyResponse(Response response,
String requestUrl, HttpServletRequest request) {
if(!response.isSigned()) {
debug.message("verifyResponse: Response is not signed");
return false;
}
if (!response.isSignatureValid()) {
debug.message("verifyResponse: Response's signature is invalid.");
return false;
}
// check Recipient == this server's POST profile URL(requestURL)
String recipient = response.getRecipient();
if ((recipient == null) || (recipient.length() == 0) ||
((!equalURL(recipient, requestUrl)) &&
(!equalURL(recipient,getLBURL(requestUrl, request))))) {
debug.error("verifyResponse : Incorrect Recipient.");
return false;
}
// check status of the Response
if (!response.getStatus().getStatusCode().getValue().endsWith(
SAMLConstants.STATUS_CODE_SUCCESS_NO_PREFIX)) {
debug.error("verifyResponse : Incorrect StatusCode value.");
return false;
}
return true;
} | 1 | Java | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
protected void untar(File destDir, InputStream inputStream) throws IOException {
TarArchiveInputStream tin = new TarArchiveInputStream(inputStream);
TarArchiveEntry tarEntry = null;
while ((tarEntry = tin.getNextTarEntry()) != null) {
File destEntry = new File(destDir, tarEntry.getName());
if (!destEntry.toPath().normalize().startsWith(destDir.toPath().normalize())) {
throw new IllegalArgumentException("Zip archives with files escaping their root directory are not allowed.");
}
File parent = destEntry.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (tarEntry.isDirectory()) {
destEntry.mkdirs();
} else {
FileOutputStream fout = new FileOutputStream(destEntry);
try {
IOUtils.copy(tin, fout);
} finally {
fout.close();
}
}
}
tin.close();
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
public void testUntarZipSlip() throws IOException {
FileProjectManager manager = new FileProjectManagerStub(workspaceDir);
File tempDir = TestUtils.createTempDirectory("openrefine-project-import-zip-slip-test");
try {
File subDir = new File(tempDir, "dest");
InputStream stream = FileProjectManagerTests.class.getClassLoader().getResourceAsStream("zip-slip.tar");
assertThrows(IllegalArgumentException.class, () -> manager.untar(subDir, stream));
} finally {
tempDir.delete();
}
} | 1 | Java | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
public URI toURI() {
try {
return new URI(
"jdbc:" + databaseType.toLowerCase(),
databaseHost + ((databasePort == 0) ? "" : (":" + databasePort)),
"/" + databaseName,
useSSL ? "useSSL=true" : null,
null
);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
public Connection getConnection(DatabaseConfiguration databaseConfiguration, boolean forceNewConnection)
throws DatabaseServiceException {
try {
// logger.info("connection::{}, forceNewConnection: {}", connection, forceNewConnection);
if (connection != null && !forceNewConnection) {
// logger.debug("connection closed::{}", connection.isClosed());
if (!connection.isClosed()) {
if (logger.isDebugEnabled()) {
logger.debug("Returning existing connection::{}", connection);
}
return connection;
}
}
Class.forName(type.getClassPath());
DriverManager.setLoginTimeout(10);
String dbURL = databaseConfiguration.toURI().toString();
connection = DriverManager.getConnection(dbURL, databaseConfiguration.getDatabaseUser(),
databaseConfiguration.getDatabasePassword());
if (logger.isDebugEnabled()) {
logger.debug("*** Acquired New connection for ::{} **** ", dbURL);
}
return connection;
} catch (ClassNotFoundException e) {
logger.error("Jdbc Driver not found", e);
throw new DatabaseServiceException(e.getMessage());
} catch (SQLException e) {
logger.error("SQLException::Couldn't get a Connection!", e);
throw new DatabaseServiceException(true, e.getSQLState(), e.getErrorCode(), e.getMessage());
}
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
public Connection getConnection(DatabaseConfiguration databaseConfiguration, boolean forceNewConnection)
throws DatabaseServiceException {
try {
if (connection != null && !forceNewConnection) {
// logger.info("connection closed::{}", connection.isClosed());
if (!connection.isClosed()) {
if (logger.isDebugEnabled()) {
logger.debug("Returning existing connection::{}", connection);
}
return connection;
}
}
String dbURL = databaseConfiguration.toURI().toString();
Class.forName(type.getClassPath());
// logger.info("*** type.getClassPath() ::{}, {}**** ", type.getClassPath());
DriverManager.setLoginTimeout(10);
connection = DriverManager.getConnection(dbURL, databaseConfiguration.getDatabaseUser(),
databaseConfiguration.getDatabasePassword());
if (logger.isDebugEnabled()) {
logger.debug("*** Acquired New connection for ::{} **** ", dbURL);
}
return connection;
} catch (ClassNotFoundException e) {
logger.error("Jdbc Driver not found", e);
throw new DatabaseServiceException(e.getMessage());
} catch (SQLException e) {
logger.error("SQLException::Couldn't get a Connection!", e);
throw new DatabaseServiceException(true, e.getSQLState(), e.getErrorCode(), e.getMessage());
}
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
public Connection getConnection(DatabaseConfiguration databaseConfiguration, boolean forceNewConnection)
throws DatabaseServiceException {
try {
// logger.info("connection::{}, forceNewConnection: {}", connection, forceNewConnection);
if (connection != null && !forceNewConnection) {
// logger.info("connection closed::{}", connection.isClosed());
if (!connection.isClosed()) {
if (logger.isDebugEnabled()) {
logger.debug("Returning existing connection::{}", connection);
}
return connection;
}
}
Class.forName(type.getClassPath());
DriverManager.setLoginTimeout(10);
String dbURL = databaseConfiguration.toURI().toString();
connection = DriverManager.getConnection(dbURL, databaseConfiguration.getDatabaseUser(),
databaseConfiguration.getDatabasePassword());
logger.debug("*** Acquired New connection for ::{} **** ", dbURL);
return connection;
} catch (ClassNotFoundException e) {
logger.error("Jdbc Driver not found", e);
throw new DatabaseServiceException(e.getMessage());
} catch (SQLException e) {
logger.error("SQLException::Couldn't get a Connection!", e);
throw new DatabaseServiceException(true, e.getSQLState(), e.getErrorCode(), e.getMessage());
}
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
public static String getDatabaseUrl(DatabaseConfiguration dbConfig) {
try {
URI uri = new URI("jdbc:" + dbConfig.getDatabaseType().toLowerCase(), dbConfig.getDatabaseName(), null);
return uri.toASCIIString();
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
public void testToURI() {
DatabaseConfiguration config = new DatabaseConfiguration();
config.setDatabaseType("mysql");
config.setDatabaseHost("my.host");
// maliciously crafted database name which attempts to enable local file reads for an exploit
config.setDatabaseName("test?allowLoadLocalInfile=true#");
String url = config.toURI().toString();
// the database name is escaped, preventing the exploit
assertEquals(url, "jdbc:mysql://my.host/test%3FallowLoadLocalInfile=true%23");
} | 1 | Java | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
protected AbstractRequestContextBuilder(boolean server, RpcRequest rpcReq, URI uri) {
this.server = server;
req = null;
this.rpcReq = requireNonNull(rpcReq, "rpcReq");
method = HttpMethod.POST;
requireNonNull(uri, "uri");
authority = firstNonNull(uri.getRawAuthority(), FALLBACK_AUTHORITY);
sessionProtocol = getSessionProtocol(uri);
if (server) {
String path = uri.getRawPath();
final String query = uri.getRawQuery();
if (query != null) {
path += '?' + query;
}
final RequestTarget reqTarget = RequestTarget.forServer(path);
if (reqTarget == null) {
throw new IllegalArgumentException("invalid uri: " + uri);
}
this.reqTarget = reqTarget;
} else {
reqTarget = DefaultRequestTarget.createWithoutValidation(
RequestTargetForm.ORIGIN, null, null,
uri.getRawPath(), uri.getRawPath(), uri.getRawQuery(), uri.getRawFragment());
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public Boolean allowSemicolonInPathComponent() {
return false;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public static boolean allowSemicolonInPathComponent() {
return ALLOW_SEMICOLON_IN_PATH_COMPONENT;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
default Boolean allowSemicolonInPathComponent() {
return null;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
static RequestTarget forServer(String reqTarget) {
requireNonNull(reqTarget, "reqTarget");
return DefaultRequestTarget.forServer(reqTarget, Flags.allowSemicolonInPathComponent(),
Flags.allowDoubleDotsInQueryString());
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public Boolean allowSemicolonInPathComponent() {
return getBoolean("allowSemicolonInPathComponent");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public static RequestTarget forServer(String reqTarget, boolean allowSemicolonInPathComponent,
boolean allowDoubleDotsInQueryString) {
final RequestTarget cached = RequestTargetCache.getForServer(reqTarget);
if (cached != null) {
return cached;
}
return slowForServer(reqTarget, allowSemicolonInPathComponent, allowDoubleDotsInQueryString);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private DefaultRequestTarget(RequestTargetForm form, @Nullable String scheme, @Nullable String authority,
String path, String maybePathWithMatrixVariables,
@Nullable String query, @Nullable String fragment) {
assert (scheme != null && authority != null) ||
(scheme == null && authority == null) : "scheme: " + scheme + ", authority: " + authority;
this.form = form;
this.scheme = scheme;
this.authority = authority;
this.path = path;
this.maybePathWithMatrixVariables = maybePathWithMatrixVariables;
this.query = query;
this.fragment = fragment;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public static RequestTarget createWithoutValidation(
RequestTargetForm form, @Nullable String scheme, @Nullable String authority,
String path, String pathWithMatrixVariables, @Nullable String query, @Nullable String fragment) {
return new DefaultRequestTarget(
form, scheme, authority, path, pathWithMatrixVariables, query, fragment);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static RequestTarget slowAbsoluteFormForClient(String reqTarget, int authorityPos) {
// Extract scheme and authority while looking for path.
final URI schemeAndAuthority;
final String scheme = reqTarget.substring(0, authorityPos - 3);
final int nextPos = findNextComponent(reqTarget, authorityPos);
final String authority;
if (nextPos < 0) {
// Found no other components after authority
authority = reqTarget.substring(authorityPos);
} else {
// Path, query or fragment exists.
authority = reqTarget.substring(authorityPos, nextPos);
}
// Reject a URI with an empty authority.
if (authority.isEmpty()) {
return null;
}
// Normalize scheme and authority.
schemeAndAuthority = normalizeSchemeAndAuthority(scheme, authority);
if (schemeAndAuthority == null) {
// Invalid scheme or authority.
return null;
}
if (nextPos < 0) {
return new DefaultRequestTarget(RequestTargetForm.ABSOLUTE,
schemeAndAuthority.getScheme(),
schemeAndAuthority.getRawAuthority(),
"/",
"/", null,
null);
}
return slowForClient(reqTarget, schemeAndAuthority, nextPos);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public String maybePathWithMatrixVariables() {
return maybePathWithMatrixVariables;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public static String removeMatrixVariables(String path) {
int semicolonIndex = path.indexOf(';');
if (semicolonIndex < 0) {
return path;
}
if (semicolonIndex == 0 || path.charAt(semicolonIndex - 1) == '/') {
// Invalid matrix variable e.g. /;a=b/foo
return null;
}
int subStringStartIndex = 0;
try (TemporaryThreadLocals threadLocals = TemporaryThreadLocals.acquire()) {
final StringBuilder sb = threadLocals.stringBuilder();
for (;;) {
sb.append(path, subStringStartIndex, semicolonIndex);
final int slashIndex = path.indexOf('/', semicolonIndex + 1);
if (slashIndex < 0) {
return sb.toString();
}
subStringStartIndex = slashIndex;
semicolonIndex = path.indexOf(';', subStringStartIndex + 1);
if (semicolonIndex < 0) {
sb.append(path, subStringStartIndex, path.length());
return sb.toString();
}
if (path.charAt(semicolonIndex - 1) == '/') {
// Invalid matrix variable e.g. /prefix/;a=b/foo
return null;
}
}
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public static String mappedPath(ServiceRequestContext ctx) {
final RequestTarget requestTarget = ctx.routingContext().requestTarget();
final String pathWithMatrixVariables = requestTarget.maybePathWithMatrixVariables();
if (pathWithMatrixVariables.equals(ctx.path())) {
return ctx.mappedPath();
}
// The request path contains matrix variables. e.g. "/foo/bar/users;name=alice"
final String prefix = ctx.path().substring(0, ctx.path().length() - ctx.mappedPath().length());
// The prefix is now `/foo/bar`
if (!pathWithMatrixVariables.startsWith(prefix)) {
// The request path has matrix variables in the wrong place. e.g. "/foo;name=alice/bar/users"
return null;
}
final String mappedPath = pathWithMatrixVariables.substring(prefix.length());
if (mappedPath.charAt(0) != '/') {
// Again, the request path has matrix variables in the wrong place. e.g. "/foo/bar;/users"
return null;
}
return mappedPath;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private MappedPathUtil() {} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private ExactPathMapping(String prefix, String exactPath) {
if (!Flags.allowSemicolonInPathComponent()) {
checkArgument(prefix.indexOf(';') < 0, "prefix: %s (expected not to have a ';')", prefix);
checkArgument(exactPath.indexOf(';') < 0, "exactPath: %s (expected not to have a ';')", exactPath);
}
this.prefix = prefix;
this.exactPath = ensureAbsolutePath(exactPath, "exactPath");
paths = ImmutableList.of(exactPath, exactPath);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
PrefixPathMapping(String prefix, boolean stripPrefix) {
checkArgument(Flags.allowSemicolonInPathComponent() || prefix.indexOf(';') < 0,
"prefix: %s (expected not to have a ';')", prefix);
prefix = ensureAbsolutePath(prefix, "prefix");
if (!prefix.endsWith("/")) {
prefix += '/';
}
this.prefix = prefix;
this.stripPrefix = stripPrefix;
final String triePath = prefix + '*';
paths = ImmutableList.of(prefix, triePath);
pathPattern = triePath;
strVal = PREFIX + prefix + " (stripPrefix: " + stripPrefix + ')';
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
default RoutingContext withPath(String path) {
requireNonNull(path, "path");
final RequestTarget oldReqTarget = requestTarget();
final RequestTarget newReqTarget =
DefaultRequestTarget.createWithoutValidation(
oldReqTarget.form(),
oldReqTarget.scheme(),
oldReqTarget.authority(),
removeMatrixVariables(path),
path,
oldReqTarget.query(),
oldReqTarget.fragment());
return new RoutingContextWrapper(this) {
@Override
public RequestTarget requestTarget() {
return newReqTarget;
}
};
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void shouldHandleSquareBracketsInPath(Mode mode) {
assertAccepted(parse(mode, "/@/:[]!$&'()*+,="), "/@/:%5B%5D!$&'()*+,=");
assertAccepted(parse(mode, "/%40%2F%3A%5B%5D%21%24%26%27%28%29%2A%2B%2C%3D%3F"),
"/@%2F:%5B%5D!$&'()*+,=%3F");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static RequestTarget forServer(String rawPath, boolean allowSemicolonInPathComponent) {
final RequestTarget res = DefaultRequestTarget.forServer(rawPath, allowSemicolonInPathComponent, false);
if (res != null) {
logger.info("forServer({}) => path: {}, query: {}", rawPath, res.path(), res.query());
} else {
logger.info("forServer({}) => null", rawPath);
}
return res;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void testRemoveMatrixVariables() {
assertThat(removeMatrixVariables("/foo")).isEqualTo("/foo");
assertThat(removeMatrixVariables("/foo;")).isEqualTo("/foo");
assertThat(removeMatrixVariables("/foo/")).isEqualTo("/foo/");
assertThat(removeMatrixVariables("/foo/bar")).isEqualTo("/foo/bar");
assertThat(removeMatrixVariables("/foo/bar;")).isEqualTo("/foo/bar");
assertThat(removeMatrixVariables("/foo/bar/")).isEqualTo("/foo/bar/");
assertThat(removeMatrixVariables("/foo;/bar")).isEqualTo("/foo/bar");
assertThat(removeMatrixVariables("/foo;/bar;")).isEqualTo("/foo/bar");
assertThat(removeMatrixVariables("/foo;/bar/")).isEqualTo("/foo/bar/");
assertThat(removeMatrixVariables("/foo;a=b/bar")).isEqualTo("/foo/bar");
assertThat(removeMatrixVariables("/foo;a=b/bar;")).isEqualTo("/foo/bar");
assertThat(removeMatrixVariables("/foo;a=b/bar/")).isEqualTo("/foo/bar/");
assertThat(removeMatrixVariables("/foo;a=b/bar/baz")).isEqualTo("/foo/bar/baz");
assertThat(removeMatrixVariables("/foo;a=b/bar/baz;")).isEqualTo("/foo/bar/baz");
assertThat(removeMatrixVariables("/foo;a=b/bar/baz/")).isEqualTo("/foo/bar/baz/");
assertThat(removeMatrixVariables("/foo;a=b/bar;/baz")).isEqualTo("/foo/bar/baz");
assertThat(removeMatrixVariables("/foo;a=b/bar;/baz;")).isEqualTo("/foo/bar/baz");
assertThat(removeMatrixVariables("/foo;a=b/bar;/baz/")).isEqualTo("/foo/bar/baz/");
assertThat(removeMatrixVariables("/foo;a=b/bar;c=d/baz")).isEqualTo("/foo/bar/baz");
assertThat(removeMatrixVariables("/foo;a=b/bar;c=d/baz;")).isEqualTo("/foo/bar/baz");
assertThat(removeMatrixVariables("/foo;a=b/bar;c=d/baz/")).isEqualTo("/foo/bar/baz/");
// Invalid
assertThat(removeMatrixVariables("/;a=b")).isNull();
assertThat(removeMatrixVariables("/prefix/;a=b")).isNull();
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void serverShouldHandleReservedCharacters() {
assertAccepted(forServer("/#/:@!$&'()*+,=?a=/#/:[]@!$&'()*+,="),
"/%23/:@!$&'()*+,=",
"a=/%23/:[]@!$&'()*+,=");
assertAccepted(forServer("/%23%2F%3A%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F" +
"?a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F"),
"/%23%2F:@!$&'()*+,%3B=%3F",
"a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void reserveSemicolonWhenAllowed() {
// '%3B' is decoded into ';' when allowSemicolonInPathComponent is true.
assertAccepted(forServer("/abc%3B?a=%3B", true), "/abc;", "a=%3B");
assertAccepted(forServer("/abc%3B?a=%3B"), "/abc%3B", "a=%3B");
assertAccepted(forServer("/abc%3B", true), "/abc;");
assertAccepted(forServer("/abc%3B"), "/abc%3B");
// Client always decodes '%3B' into ';'.
assertAccepted(forClient("/abc%3B?a=%3B"), "/abc;", "a=%3B");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void serverShouldRemoveMatrixVariablesWhenNotAllowed() {
// Not allowed
assertAccepted(forServer("/;a=b?c=d;e=f"), "/", "c=d;e=f");
// Allowed.
assertAccepted(forServer("/;a=b?c=d;e=f", true), "/;a=b", "c=d;e=f");
// '%3B' should never be decoded into ';'.
assertAccepted(forServer("/%3B?a=b%3Bc=d"), "/%3B", "a=b%3Bc=d");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void shouldReserveQuestionMark() throws URISyntaxException {
// '%3F' must not be decoded into '?'.
assertAccepted(forServer("/abc%3F.json?a=%3F"), "/abc%3F.json", "a=%3F");
assertAccepted(forClient("/abc%3F.json?a=%3F"), "/abc%3F.json", "a=%3F");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void stripMatrixVariables() throws InterruptedException {
final AggregatedHttpResponse response = server.blockingWebClient().get("/foo;a=b");
assertThat(response.headers().status()).isSameAs(HttpStatus.OK);
final ServiceRequestContextCaptor captor = server.requestContextCaptor();
final ServiceRequestContext sctx = captor.poll();
assertThat(sctx.path()).isEqualTo("/foo");
assertThat(sctx.routingContext().requestTarget().maybePathWithMatrixVariables())
.isEqualTo("/foo;a=b");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
static final ServerExtension server = new ServerExtension() {
@Override
protected void configure(ServerBuilder sb) throws Exception {
sb.service("/foo", (ctx, req) -> HttpResponse.of(200));
}
}; | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void notAllowSemicolon() {
assertThatThrownBy(() -> Route.builder().path("/foo;")).isInstanceOf(
IllegalArgumentException.class);
assertThatThrownBy(() -> Route.builder().path("/foo/{bar};")).isInstanceOf(
IllegalArgumentException.class);
assertThatThrownBy(() -> Route.builder().path("/bar/:baz;")).isInstanceOf(
IllegalArgumentException.class);
assertThatThrownBy(() -> Route.builder().path("exact:/:foo/bar;")).isInstanceOf(
IllegalArgumentException.class);
assertThatThrownBy(() -> Route.builder().path("prefix:/bar/baz;")).isInstanceOf(
IllegalArgumentException.class);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void exceptionHandler() {
throw new BaseException("exception handler");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void customException() {
throw new CustomException();
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public ResponseEntity<Map<String, Object>> onBaseException(Throwable t) {
final Map<String, Object> body = ImmutableMap.<String, Object>builder()
.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value())
.put("message", t.getMessage())
.build();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
BaseException(String message) {
super(message);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void runtimeException() {
throw new RuntimeException("runtime exception");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void globalExceptionHandler() {
throw new GlobalBaseException("global exception handler");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
GlobalBaseException(String message) {
super(message);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public ResponseEntity<Map<String, Object>> onGlobalBaseException(Throwable t) {
final String message = t.getMessage();
final Map<String, Object> body = ImmutableMap.of("status", HttpStatus.INTERNAL_SERVER_ERROR.value(),
"message", message);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public Greeting(String content) {
this.content = content;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public String getContent() {
return content;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public ResponseEntity<Greeting> greetingSync(
@RequestParam(value = "name", defaultValue = "World") String name) {
return ResponseEntity.ok(new Greeting(String.format(template, name)));
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
List<Integer> findPet(
@MatrixVariable(name = "q", pathVar = "ownerId") int q1,
@MatrixVariable(name = "q", pathVar = "petId") int q2) {
return ImmutableList.of(q1, q2);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
JettyServletWebServerFactory jettyServletWebServerFactory(
ObjectProvider<JettyServerCustomizer> serverCustomizers) {
final JettyServletWebServerFactory factory = new ArmeriaJettyServletWebServerFactory();
factory.getServerCustomizers().addAll(serverCustomizers.orderedStream().toList());
return factory;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
protected JettyWebServer getJettyWebServer(Server server) {
return new JettyWebServer(server, true);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public static void main(String[] args) {
SpringApplication.run(SpringJettyApplication.class, args);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public ArmeriaServerConfigurator armeriaTomcat(WebServerApplicationContext applicationContext) {
final WebServer webServer = applicationContext.getWebServer();
if (webServer instanceof JettyWebServer) {
final Server jettyServer = ((JettyWebServer) webServer).getServer();
return serverBuilder -> serverBuilder.service("prefix:/jetty/api/rest/v1",
JettyService.of(jettyServer));
}
return serverBuilder -> {};
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static void assertUpStatus(AggregatedHttpResponse res) throws IOException {
assertThat(res.status()).isEqualTo(HttpStatus.OK);
assertThat(res.contentType().toString()).isEqualTo("application/vnd.spring-boot.actuator.v3+json");
final Map<String, Object> values = OBJECT_MAPPER.readValue(res.content().array(), JSON_MAP);
assertThat(values).containsEntry("status", "UP");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void additionalPath() throws Exception {
String path = "/internal/actuator/health/foo";
assertUpStatus(managementClient.get(path).aggregate().join());
assertThat(armeriaClient.get(path).aggregate().join().status()).isSameAs(HttpStatus.NOT_FOUND);
path = "/internal/actuator/health/bar";
assertUpStatus(managementClient.get(path).aggregate().join());
assertThat(armeriaClient.get(path).aggregate().join().status()).isSameAs(HttpStatus.NOT_FOUND);
path = "/foohealth";
assertUpStatus(managementClient.get(path).aggregate().join());
assertThat(armeriaClient.get(path).aggregate().join().status()).isSameAs(HttpStatus.NOT_FOUND);
// barhealth is bound to Armeria port.
path = "/barhealth";
assertThat(managementClient.get(path).aggregate().join().status()).isSameAs(HttpStatus.NOT_FOUND);
assertUpStatus(armeriaClient.get(path).aggregate().join());
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void setUp() {
managementClient = WebClient.builder("http://127.0.0.1:" + managementPort).build();
armeriaClient = WebClient.builder("http://127.0.0.1:" + armeriaPort).build();
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void testHealth() throws Exception {
final AggregatedHttpResponse res = managementClient.get("/internal/actuator/health").aggregate().join();
assertUpStatus(res);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static final TypeReference<Map<String, Object>> JSON_MAP = new TypeReference<>() {}; | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void shouldReturnFormattedMessage(String path, int status, String message) throws Exception {
final ResponseEntity<String> response =
restTemplate.getForEntity(jettyBaseUrlPath(port) + path, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.valueOf(status));
assertThatJson(response.getBody()).node("status").isEqualTo(status);
assertThatJson(response.getBody()).node("message").isEqualTo(message);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static String jettyBaseUrlPath(int port) {
return "http://localhost:" + port + JETTY_BASE_PATH;
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void wrongMatrixVariables() throws Exception {
final WebClient client = WebClient.of("http://127.0.0.1:" + port);
AggregatedHttpResponse response = client.blocking().get(
JETTY_BASE_PATH + ";/owners/42;q=11/pets/21;q=22");
assertThat(response.status()).isSameAs(HttpStatus.BAD_REQUEST);
response = client.blocking().get("/jetty;wrong=place/api/rest/v1/owners/42;q=11/pets/21;q=22");
assertThat(response.status()).isSameAs(HttpStatus.BAD_REQUEST);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void matrixVariablesPreserved() throws Exception {
final WebClient client = WebClient.of("http://127.0.0.1:" + port);
final AggregatedHttpResponse response = client.blocking().get(
JETTY_BASE_PATH + "/owners/42;q=11/pets/21;q=22");
assertThat(response.contentUtf8()).isEqualTo("[11,22]");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void greetingShouldReturn404() throws Exception {
assertThat(restTemplate.getForEntity("http://localhost:" + httpPort + JETTY_BASE_PATH + "/greet",
Void.class)
.getStatusCode().value()).isEqualByComparingTo(404);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void contextLoads() {
assertThat(greetingController).isNotNull();
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public void init() throws Exception {
httpPort = server.activePorts()
.values()
.stream()
.filter(ServerPort::hasHttp)
.findAny()
.get()
.localAddress()
.getPort();
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void greetingShouldReturnDefaultMessage() throws Exception {
assertThat(restTemplate.getForObject("http://localhost:" + httpPort + JETTY_BASE_PATH + "/greeting",
String.class))
.contains("Hello, World!");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void greetingShouldReturnUsersMessage() throws Exception {
assertThat(restTemplate.getForObject("http://localhost:" + httpPort +
JETTY_BASE_PATH + "/greeting?name=Armeria",
String.class))
.contains("Hello, Armeria!");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
List<Integer> findPet(
@MatrixVariable(name = "q", pathVar = "ownerId") int q1,
@MatrixVariable(name = "q", pathVar = "petId") int q2) {
return ImmutableList.of(q1, q2);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static final TypeReference<Map<String, Object>> JSON_MAP = new TypeReference<>() {}; | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void wrongMatrixVariables() throws Exception {
final WebClient client = WebClient.of("http://127.0.0.1:" + port);
AggregatedHttpResponse response = client.blocking().get(
TOMCAT_BASE_PATH + ";/owners/42;q=11/pets/21;q=22");
assertThat(response.status()).isSameAs(HttpStatus.BAD_REQUEST);
response = client.blocking().get("/tomcat;wrong=place/api/rest/v1/owners/42;q=11/pets/21;q=22");
assertThat(response.status()).isSameAs(HttpStatus.BAD_REQUEST);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void matrixVariablesPreserved() throws Exception {
final WebClient client = WebClient.of("http://127.0.0.1:" + port);
final AggregatedHttpResponse response = client.blocking().get(
TOMCAT_BASE_PATH + "/owners/42;q=11/pets/21;q=22");
assertThat(response.contentUtf8()).isEqualTo("[11,22]");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static void fillRequest(
ServiceRequestContext ctx, AggregatedHttpRequest aReq, Request jReq, String mappedPath) {
DispatcherTypeUtil.setRequestType(jReq);
jReq.setAsyncSupported(true, null);
jReq.setSecure(ctx.sessionProtocol().isTls());
jReq.setMetaData(toRequestMetadata(ctx, aReq, mappedPath));
final HttpHeaders trailers = aReq.trailers();
if (!trailers.isEmpty()) {
final HttpField[] httpFields = trailers.stream()
.map(e -> new HttpField(e.getKey().toString(), e.getValue()))
.toArray(HttpField[]::new);
jReq.setTrailerHttpFields(HttpFields.from(httpFields));
}
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static MetaData.Request toRequestMetadata(ServiceRequestContext ctx, AggregatedHttpRequest aReq,
String mappedPath) {
// Construct the HttpURI
final StringBuilder uriBuf = new StringBuilder();
final RequestHeaders aHeaders = aReq.headers();
uriBuf.append(ctx.sessionProtocol().isTls() ? "https" : "http");
uriBuf.append("://");
uriBuf.append(aHeaders.authority());
final RequestTarget requestTarget = ctx.routingContext().requestTarget();
if (requestTarget.query() != null) {
mappedPath = mappedPath + '?' + requestTarget.query();
}
uriBuf.append(mappedPath);
final HttpURI uri = HttpURI.build(HttpURI.build(uriBuf.toString()))
.asImmutable();
final HttpField[] fields = aHeaders.stream().map(header -> {
final AsciiString k = header.getKey();
final String v = header.getValue();
if (k.charAt(0) != ':') {
return new HttpField(k.toString(), v);
}
if (HttpHeaderNames.AUTHORITY.equals(k) && !aHeaders.contains(HttpHeaderNames.HOST)) {
// Convert `:authority` to `host`.
return new HttpField(HttpHeaderNames.HOST.toString(), v);
}
return null;
}).filter(Objects::nonNull).toArray(HttpField[]::new);
final HttpFields jHeaders = HttpFields.from(fields);
return new MetaData.Request(aHeaders.method().name(), uri,
ctx.sessionProtocol().isMultiplex() ? HttpVersion.HTTP_2
: HttpVersion.HTTP_1_1,
jHeaders, aReq.content().length());
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
ArmeriaServerHttpRequest(ServiceRequestContext ctx,
HttpRequest req,
DataBufferFactoryWrapper<?> factoryWrapper) {
super(uri(ctx, req), null, springHeaders(req.headers()));
this.ctx = requireNonNull(ctx, "ctx");
this.req = req;
body = Flux.from(req).cast(HttpData.class).map(factoryWrapper::toDataBuffer)
// Guarantee that the context is accessible from a controller method
// when a user specify @RequestBody in order to convert a request body into an object.
.publishOn(Schedulers.fromExecutor(ctx.eventLoop()));
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
private static URI uri(ServiceRequestContext ctx, HttpRequest req) {
final String scheme = req.scheme();
final String authority = req.authority();
// Server side Armeria HTTP request always has the scheme and authority.
assert scheme != null;
assert authority != null;
final RequestTarget requestTarget = ctx.routingContext().requestTarget();
String path = requestTarget.maybePathWithMatrixVariables();
if (requestTarget.query() != null) {
path = path + '?' + requestTarget.query();
}
return URI.create(scheme + "://" + authority + path);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
Flux<Integer> findPet(
@MatrixVariable(name = "q", pathVar = "ownerId") int q1,
@MatrixVariable(name = "q", pathVar = "petId") int q2) {
return Flux.just(q1, q2);
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
void foo() throws Exception {
final WebClient client = WebClient.of("http://127.0.0.1:" + port);
final AggregatedHttpResponse response = client.blocking().get("/owners/42;q=11/pets/21;q=22");
assertThat(response.contentUtf8()).isEqualTo("[11,22]");
} | 1 | Java | NVD-CWE-noinfo | null | null | null | safe |
public GuiCraftingPipe(EntityPlayer player, IInventory dummyInventory, BaseLogicCrafting logic, boolean isAdvancedSat, boolean isSplitedCrafting) {
super(null);
_player = player;
this.isAdvancedSat = isAdvancedSat;
this.isSplitedCrafting = isSplitedCrafting;
if(!isAdvancedSat && !isSplitedCrafting) {
xSize = 177;
ySize = 187;
} else {
xSize = 177;
ySize = 187 + 30;
}
DummyContainer dummy = new DummyContainer(player.inventory, dummyInventory);
dummy.addNormalSlotsForPlayerInventory(8, ySize - 82);
//Input slots
for(int l = 0; l < 9; l++) {
dummy.addDummySlot(l, 8 + l * 18, 18);
}
//Output slot
if(!isAdvancedSat) {
dummy.addDummySlot(9, 85, 55);
} else {
dummy.addDummySlot(9, 85, 105);
}
this.inventorySlots = dummy;
_logic = logic;
buttonarray = new GuiButton[6];
normalButtonArray = new GuiButton[6];
advancedSatButtonArray = new GuiButton[9][2];
for(int i=0;i<9;i++) {
advancedSatButtonArray[i] = new GuiButton[2];
}
} | 1 | Java | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
public void initGui() {
super.initGui();
if(!isAdvancedSat) {
controlList.add(normalButtonArray[0] = new SmallGuiButton(0, (width-xSize) / 2 + 155, (height - ySize) / 2 + 50, 10,10, ">"));
controlList.add(normalButtonArray[1] = new SmallGuiButton(1, (width-xSize) / 2 + 120, (height - ySize) / 2 + 50, 10,10, "<"));
}
if(!isAdvancedSat) {
controlList.add(normalButtonArray[2] = new SmallGuiButton(3, (width-xSize) / 2 + 39, (height - ySize) / 2 + 50, 37,10, "Import"));
controlList.add(normalButtonArray[3] = new SmallGuiButton(4, (width-xSize) / 2 + 6, (height - ySize) / 2 + 50, 28,10, "Open"));
for(int i = 0; i < 6; i++) {
controlList.add(buttonarray[i] = new SmallGuiButton(5 + i, (width-xSize) / 2 + 12 + 18 * i, (height - ySize) / 2 + 30, 10,10, ">"));
buttonarray[i].drawButton = false;
}
controlList.add(normalButtonArray[4] = new SmallGuiButton(20, (width-xSize) / 2 + 155, (height - ySize) / 2 + 85, 10,10, ">"));
controlList.add(normalButtonArray[5] = new SmallGuiButton(21, (width-xSize) / 2 + 120, (height - ySize) / 2 + 85, 10,10, "<"));
} else {
for(int i=0;i<9;i++) {
controlList.add(advancedSatButtonArray[i][0] = new SmallGuiButton(30 + i, (width-xSize) / 2 + 10 + 18 * i, (height - ySize) / 2 + 40, 15,10, "/\\"));
controlList.add(advancedSatButtonArray[i][1] = new SmallGuiButton(40 + i, (width-xSize) / 2 + 10 + 18 * i, (height - ySize) / 2 + 70, 15,10, "\\/"));
}
controlList.add(normalButtonArray[2] = new SmallGuiButton(3, (width-xSize) / 2 + 39, (height - ySize) / 2 + 100, 37,10, "Import"));
controlList.add(normalButtonArray[3] = new SmallGuiButton(4, (width-xSize) / 2 + 6, (height - ySize) / 2 + 100, 28,10, "Open"));
controlList.add(normalButtonArray[4] = new SmallGuiButton(20, (width-xSize) / 2 + 155, (height - ySize) / 2 + 105, 10,10, ">"));
controlList.add(normalButtonArray[5] = new SmallGuiButton(21, (width-xSize) / 2 + 120, (height - ySize) / 2 + 105, 10,10, "<"));
}
} | 1 | Java | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
protected void actionPerformed(GuiButton guibutton) {
if(5 <= guibutton.id && guibutton.id < 11) {
_logic.handleStackMove(guibutton.id - 5);
}
if(30 <= guibutton.id && guibutton.id < 40) {
_logic.setNextSatellite(_player, guibutton.id - 30);
}
if(40 <= guibutton.id && guibutton.id < 50) {
_logic.setPrevSatellite(_player, guibutton.id - 40);
}
switch(guibutton.id){
case 0:
_logic.setNextSatellite(_player);
return;
case 1:
_logic.setPrevSatellite(_player);
return;
/*case 2:
_logic.paintPathToSatellite();
return;*/
case 3:
_logic.importFromCraftingTable(_player);
return;
case 4:
_logic.openAttachedGui(_player);
return;
case 20:
_logic.priorityUp(_player);
return;
case 21:
_logic.priorityDown(_player);
return;
default:
super.actionPerformed(guibutton);
return;
}
} | 1 | Java | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
protected void drawGuiContainerBackgroundLayer(float f, int x, int y) {
BasicGuiHelper.drawGuiBackGround(mc, guiLeft, guiTop, guiLeft + xSize, guiTop + ySize, zLevel, true, true, true, true, true);
if(!isAdvancedSat) {
drawRect(guiLeft + 116, guiTop + 4, guiLeft + 170, guiTop + 70, 0xff8B8B8B);
}
for(int i=0; i<9;i++) {
BasicGuiHelper.drawSlotBackground(mc, guiLeft + 7 + (18*i), guiTop + 17);
}
if(!isAdvancedSat) {
BasicGuiHelper.drawBigSlotBackground(mc, guiLeft + 80, guiTop + 50);
} else {
BasicGuiHelper.drawBigSlotBackground(mc, guiLeft + 80, guiTop + 100);
}
BasicGuiHelper.drawPlayerInventoryBackground(mc, guiLeft + 8, guiTop + ySize - 82);
if(!isAdvancedSat) {
for(int count=36; count<42;count++) {
Slot slot = inventorySlots.getSlot(count);
if(slot != null && slot.getStack() != null && slot.getStack().getMaxStackSize() < 2) {
drawRect(guiLeft + 18 + (18 * (count-36)), guiTop + 18, guiLeft + 18 + (18 * (count-36)) + 16, guiTop + 18 + 16, 0xFFFF0000);
buttonarray[count - 36].drawButton = true;
} else {
buttonarray[count - 36].drawButton = false;
}
}
}
} | 1 | Java | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
protected void drawGuiContainerForegroundLayer(int par1, int par2) {
fontRenderer.drawString("Inputs", 18, 7, 0x404040);
fontRenderer.drawString("Inventory", 10, ySize - 93, 0x404040);
if(!isAdvancedSat) {
fontRenderer.drawString("Output", 77, 40, 0x404040);
fontRenderer.drawString("Satellite", 123, 7, 0x404040);
if (_logic.satelliteId == 0) {
fontRenderer.drawString("Off", 135, 52, 0x404040);
} else {
fontRenderer.drawString(""+_logic.satelliteId , 146 - fontRenderer.getStringWidth(""+_logic.satelliteId) , 52, 0x404040);
}
fontRenderer.drawString("Priority:" , 123 , 75, 0x404040);
fontRenderer.drawString(""+_logic.priority , 143 - (fontRenderer.getStringWidth(""+_logic.priority) / 2) , 87, 0x404040);
} else {
for(int i=0; i<9;i++) {
if (_logic.advancedSatelliteIdArray[i] == 0) {
fontRenderer.drawString("Off", 10 + (i * 18), 57, 0x404040);
} else {
fontRenderer.drawString(""+_logic.advancedSatelliteIdArray[i] , 20 - fontRenderer.getStringWidth(""+_logic.advancedSatelliteIdArray[i]) + (i * 18), 57, 0x404040);
}
}
fontRenderer.drawString("Output", 77, 90, 0x404040);
fontRenderer.drawString("Priority:" , 123 , 95, 0x404040);
fontRenderer.drawString(""+_logic.priority , 143 - (fontRenderer.getStringWidth(""+_logic.priority) / 2) , 107, 0x404040);
}
} | 1 | Java | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
public void loadUpgrades() {
registerUpgrade(SNEAKY_UP, "Sneaky Upgrade (UP)", SneakyUpgradeUP.class);
registerUpgrade(SNEAKY_DOWN, "Sneaky Upgrade (DOWN)", SneakyUpgradeDOWN.class);
registerUpgrade(SNEAKY_NORTH, "Sneaky Upgrade (NORTH)", SneakyUpgradeNORTH.class);
registerUpgrade(SNEAKY_SOUTH, "Sneaky Upgrade (SOUTH)", SneakyUpgradeSOUTH.class);
registerUpgrade(SNEAKY_EAST, "Sneaky Upgrade (EAST)", SneakyUpgradeEAST.class);
registerUpgrade(SNEAKY_WEST, "Sneaky Upgrade (WEST)", SneakyUpgradeWEST.class);
registerUpgrade(CONNECTION_UP, "Disconnection Upgrade (UP)", ConnectionUpgradeUP.class, 9 * 16 + 7);
registerUpgrade(CONNECTION_DOWN, "Disconnection Upgrade (DOWN)", ConnectionUpgradeDOWN.class, 9 * 16 + 8);
registerUpgrade(CONNECTION_NORTH, "Disconnection Upgrade (NORTH)", ConnectionUpgradeNORTH.class, 9 * 16 + 9);
registerUpgrade(CONNECTION_SOUTH, "Disconnection Upgrade (SOUTH)", ConnectionUpgradeSOUTH.class, 9 * 16 + 10);
registerUpgrade(CONNECTION_EAST, "Disconnection Upgrade (EAST)", ConnectionUpgradeEAST.class, 9 * 16 + 11);
registerUpgrade(CONNECTION_WEST, "Disconnection Upgrade (WEST)", ConnectionUpgradeWEST.class, 9 * 16 + 12);
registerUpgrade(SPEED, "Item Speed Upgrade", SpeedUpgrade.class, 9 * 16 + 6);
registerUpgrade(ADVANCED_SAT_CRAFTINGPIPE, "Advanced Satellite Upgrade", AdvancedSatelliteUpgrade.class, 9 * 16 + 13);
registerUpgrade(SAT_DISTRIBUTING_CRAFTER, "Split Crafting Upgrade (Crafter)", SplitCraftingCrafterUpgrade.class, 9 * 16 + 14);
registerUpgrade(SAT_DISTRIBUTING_SATELITE, "Split Crafting Upgrade (Satellite)", SplitCraftingSatelliteUpgrade.class, 9 * 16 + 15);
} | 1 | Java | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.